打字稿创建具有所有关键属性但类型不同的对象副本

时间:2019-04-29 19:59:00

标签: typescript vanilla-typescript

我对获取以下内容所需使用的类型有疑问:

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

该实现应位于从Type1Type2的函数中,例如:

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

1 个答案:

答案 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 & Type2intersection type)的结果。因此,您无需进行映射,就可以拥有对象bar,该对象包含与foo相同类型的相同属性。

相关问题