首页 > 解决方案 > Why typeof does not check inheritance of class?

问题描述

how to make an example work? Why i can not use typeof in this example and what can it be replaced with?

abstract class Check {
    constructor(public field: number) {
    }
}

class Check1 extends Check {
    field1: number;
    constructor(field: number, field1:number) {
        super(field);
        this.field1 = field1;
    }
}

abstract class CheckUser {
    abstract getConstructor(): typeof Check;
}

class Check1User extends CheckUser{
    getConstructor(): typeof Check {
        return Check1;
    }
}

标签: typescripttypescript-typings

解决方案


Returning typeof Check means you have to return a type that has all the statics of Check but also have a constructor with the same arguments as that of Check. Since Check1 has another argument to it's constructor it will not be assignable to the type of the Check constructor.

You can remove the extra parameter from Checked1 and the assignment will work (ex)

You could also change the base class to take a generic type argument that must be a constructor that returns Checked:

abstract class CheckUser<T extends new (...a: never[]) => Check> {
    abstract getConstructor(): T;
}

class Check1User extends CheckUser<typeof Check1>{
    getConstructor() {
        return Check1;
    }
}

Playground Link

There might be other options as well but it depends what you want to do with getConstructor afterwards.


推荐阅读