为什么 typeof 不检查类的继承关系?

huangapple go评论84阅读模式
英文:

Why typeof does not check inheritance of class?

问题

如何使示例工作?为什么在这个示例中不能使用 typeof,以及它可以被替代为什么?

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;
    }
}
英文:

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;
    }
}

答案1

得分: 2

Returning typeof Check 意味着你必须返回一个具有 Check 的所有静态成员但也有与 Check 构造函数相同参数的类型。由于 Check1 的构造函数有额外的参数,所以它不能赋值给 Check 构造函数的类型。

你可以从 Checked1 中移除额外的参数,然后赋值就会起作用。

你还可以更改基类以接受泛型类型参数,该参数必须是返回 Checked 构造函数的构造函数:

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

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

可能还有其他选项,但这取决于你打算在之后对 getConstructor 做什么。

英文:

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&lt;T extends new (...a: never[]) =&gt; Check&gt; {
    abstract getConstructor(): T;
}

class Check1User extends CheckUser&lt;typeof Check1&gt;{
    getConstructor() {
        return Check1;
    }
}

Playground Link

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

huangapple
  • 本文由 发表于 2020年1月6日 17:52:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定