将变量从一种类型转换为另一种扩展类型

时间:2019-04-30 22:10:34

标签: typescript

假设我有

[:1]

现在,我想从interface Type1 { id: number; } interface Type2 extends Type1 { name: string; } const type1: Type1 = {id: 123}; 创建type2并将type1添加到其中。最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

最安全的方法是使用点差:

interface Type1 {
id: number;
}

interface Type2 extends Type1 {
name: string;
}

const type1: Type1 = {id: 123};
const type2: Type2 = { ...type1, name: "bob"};

您也可以使用Object.assign,但是您会放弃多余的属性检查。另一方面,如果需要,您可以使用相同的对象实例:

const type2: Type2 = Object.assign(type1, { name: "bob"}); // we assign to the object in  type1, so we are adding to that object.

const type2: Type2 = Object.assign({}, type1,{ name: "bob"}); // or we assign to a new object.

您也可以使用类型断言,但是在分配name之前,对象将处于无效的类型状态:

const type2: Type2 = type1 as Type2; // type2 is in an invalid state as name is not assigned
type2.name = "bob"
相关问题