我对获取以下内容所需使用的类型有疑问:
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
}
答案 0 :(得分:0)
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
(intersection type)的结果。因此,您无需进行映射,就可以拥有对象bar
,该对象包含与foo
相同类型的相同属性。