typescript - 将变量从一种类型转换为另一种扩展类型
问题描述
假设我有
interface Type1 {
id: number;
}
interface Type2 extends Type1 {
name: string;
}
const type1: Type1 = {id: 123};
现在我想创建并添加type2
到它。最好的方法是什么?type1
name
解决方案
最安全的方法是使用传播:
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"
推荐阅读
- azure - 如何访问部署在 Azure 上的 VS 代码
- c# - 建议:- 并行化 Web 服务请求
- c# - Process.Start 找不到可执行文件
- vue.js - Vue.js 动态输入值绑定
- laravel - Laravel:为 json 字段/列定义规则或模式
- javascript - 无法在字符串上创建属性“键”
- java - 在 Java 中查找样条函数的导数
- dart - 为什么 cupertino_icons 中的图标很少?
- linux - 日期:无效日期'2018-10-21 +1天'
- android - 如何在 Android Studio 中创建新的 Android AAR