首页 > 解决方案 > 如何从泛型 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沿代码重用合同。

标签: typescriptgenericsinheritance

解决方案


感谢您的帮助,@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);,用我原来的方法解决这两个问题。


推荐阅读