typescript - 如何从泛型 TypeScript 类型扩展?
问题描述
我想要一个类型/接口,它包含来自给定泛型类型的所有属性并添加更多属性,即扩展它。另外,我希望能够将这种类型的任何对象“向下转换”到它扩展的对象。
我永远不会实例化任何添加属性类型的新对象,因为它只会充当对象的“合同”。因此,我认为它不应该是一个类。
到目前为止,我已经尝试将这两种类型相交,如下所示:
class MyClass{
prop1: string;
prop2: string;
constructor(){
this.prop1 = '1';
this.prop2 = '2';
}
}
type MyType<T> = T & {
additionalProp: string;
}
myService.getData()
.subscribe((res: MyType<MyClass>) => {
//Do something with res.additionalProp...
//This one should *not* have "additionalProp" yet it somehow does.
let anObject: MyClass = <MyClass>res;
console.log(anObject);
//output: {prop1: '1', prop2: '2', additionalProp: 'valuefromresponse'}
});
我可能很傻,但是我还没有弄清楚为什么anObject
在我的示例中仍然MyType
引入了该属性。
为了澄清,我使用泛型而不是直接扩展MyClass
,以便能够MyType
沿代码重用合同。
解决方案
感谢您的帮助,@Aleksey L.和@Tomasz Gawel。我保持MyType
不变并选择将以下内容添加到MyClass
:
static fromObject<T extends MyClass>(o: T) {
return new MyClass(o.prop1, o.prop2);
}
我知道它使用静态方法和所有方法,但这是我能想到的最干净的解决方案。有了这个,我可以打电话let anObject: MyClass = MyClass.fromObject(res);
,用我原来的方法解决这两个问题。
推荐阅读
- python - 如何读取这个特定的 pbf 文件
- c++ - 在一定长度后从数组打印出时缺少整数
- tensorflow - 如何在 tensorboard 中可视化 K 折交叉验证
- javascript - 在 React 钩子中调用函数是可能的
- javascript - 从 e.target.parentNode 获取特定 div 后,我们如何访问它的某些属性/属性
- .net - 使用 dot Net MS Graph SDK 获取自己的用户信息时出现错误代码 406?
- python - 在 Python 中使用 get 和 requests 时如何防止下载空的 pdf 文件?
- python - 从循环创建数据集
- javascript - 如何在 Python Eel 中访问本地文件?
- java - byte byteVar = 100 有效,但 int intVar = 100L 会导致编译错误。为什么?