【问题标题】:Typescript: creating a class as a generic extension of a generic parent打字稿:创建一个类作为通用父级的通用扩展
【发布时间】:2017-12-01 17:06:16
【问题描述】:

假设我有一个通用基类和一个基接口:

interface IBase{
   // empty
}

class Base<T extend IBase> {
    someFunction<T>():T {
       return null;
    }
}

interface IChild extends IBase {
    child_value: string
} 


// this is generic class derived from the Base class
class Child<S extends IChild> extends Base<S> {


    // this function does not exists in base but
    // calls an inherited generic function
    doSomeThing(){

         this.someFunction({
            irrelevant: 'foo'
         })
    }
}

我不明白为什么上面的代码编译得很好。我在想,当从子对象(Child)调用“someFunction”时,它只会被限制为 IChild 类型的对象(具有属性“child_value”)。但是在这里它是用“不相关的”承诺调用的,编译器没有抱怨。

关于泛型,我错过了什么?如何从泛型父类派生泛型类,并将泛型类型约束为基类型的“子类型”?

我希望我的问题很清楚。

【问题讨论】:

    标签: typescript generics


    【解决方案1】:

    在您的示例中唯一可能让您失望的是,您在该基类中有两个 T 上下文。

    键入T 类扩展IBase

    class Base<T extends IBase> {
    

    键入T 表示该方法没有类型约束:

    someFunction<T>(): T {
    

    如果您希望函数具有类中的类型,则不需要类型参数:

    someFunction(): T {
    

    带有更正的完整示例

    这是一个带注释的代码示例:

    interface IBase{
       // empty
    }
    
    class Base<T extends IBase> { // <-- extends, not extend
        someFunction():T { // <-- we can use T from the class if that's what you intend, so no type parameter here
           return <any>null; // return <any>null; as otherwise T must be null
        }
    }
    
    interface IChild extends IBase {
        child_value: string
    } 
    
    
    // this is generic class derived from the Base class
    class Child<S extends IChild> extends Base<S> {
        // this function does not exists in base but
        // calls an inherited generic function
        doSomeThing() {
            const x = this.someFunction();
            return x.child_value; // <-- x.child_value autocompletion and type checking
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-13
      • 2021-07-03
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 2019-03-26
      相关资源
      最近更新 更多