首页 > 解决方案 > 将变量从一种类型转换为另一种扩展类型

问题描述

假设我有

interface Type1 {
   id: number;
}

interface Type2 extends Type1 {
   name: string;
}

const type1: Type1 = {id: 123};

现在我想创建并添加type2到它。最好的方法是什么?type1name

标签: typescript

解决方案


最安全的方法是使用传播:

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"

推荐阅读