繁体   English   中英

Typescript创建具有所有键属性但类型不同的Object副本

[英]Typescript create Object copy with all key properties but different type

我有一个问题,我需要使用以获得以下类型:

type keys = "foo" | "bar";

type Type1 = Record<keys, number>;
// Using `keyof Type1` just in case :)
type Type2 = Record<keyof Type1, boolean>;

// Created somewhere, we just have this
const foo: Type1 = {
  foo: 0,
  bar: 3
};

// How do I create a `Type2` object without manually specifying all the props?
// Given that I have all the needed keys in foo?
const bar: Type2 = ???

我已经尝试了几次使用Object.assign和对象传播而没有任何结果。

// `number` not assignable to boolean
const bar: Type2 = { ...foo }; // not working
const bar: Type2 = Object.assign({}, foo); // not working
// Not working as expected, type is `Type1 & Type2`
const bar = Object.assign({} as Type2, foo); // not working
// Working but a bit ugly no?
const bar: Type2 = Object.assign({} as Type2, foo); // Working

实现应该在从Type1映射到Type2的函数内部,如:

const foonction = (obj: Type1): Type2 => {
  // create object and map values
}

Type2已经具有与Type1相同的键,因此您所要做的就是映射属性,这些属性是对象的一部分而不是类型。 所以你的foonction可能会是这样的

const foonction = (obj: Type1): Type2 => {
    let res = <Type2>{}; 
    Object.keys(obj).forEach(key => res[key as keyof Type2] = obj[key as keyof Type1] != 0);  // Do your mapping here
    return res;
}

Object.assign将生成Type1 & Type2类型的结果( 交集类型 )。 因此,您不会进行映射,您将拥有包含与foo相同类型的相同属性的对象bar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM