繁体   English   中英

打字稿:创建一个类作为通用父级的通用扩展

[英]Typescript: creating a class as a generic extension of a generic parent

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

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”)。 但是在这里它被称为“无关”的诺言,编译器没有抱怨。

我错过了泛型的什么? 如何从通用父类派生通用类并将通用类型限制为基本类型的“子类型”?

希望我的问题清楚。

在您的示例中,唯一可能使您失望的是,该基类中有两个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

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM