用泛型重载静态方法

时间:2019-02-11 11:05:48

标签: typescript

我在实例中将实例生成器封装为静态方法,并创建了一个继承的类。

type Maybe<T> = T | undefined;

interface A {
    a: number
}

interface B extends A {
    b: number
}

class X<T extends A> {
    constructor(
        public property: T
    ) {}

    static tryCreate<T_in_X extends A>(p: T_in_X): Maybe<X<T_in_X>> {
        if (p.a === 123) { // Some check just as example.
            return new this(p);
        }
    }
}

class Y<T extends B> extends X<T> {
    static tryCreate<T_in_Y extends B>(p: T_in_Y): Maybe<Y<T_in_Y>> {
        if (p.a === 456 && p.b === 789) { // Some check just as example.
            return new this(p);
        }
    }
}

Code in Playground

我希望Y.tryCreate扩展X.tryCreate但会出现编译时错误:

Class static side 'typeof Y' incorrectly extends base class static side 'typeof X'.
  Types of property 'tryCreate' are incompatible.
    Type '<T_in_Y extends B>(p: T_in_Y) => Y<T_in_Y>' is not assignable to type '<T_in_X extends A>(p: T_in_X) => X<T_in_X>'.
      Types of parameters 'p' and 'p' are incompatible.
        Type 'T_in_X' is not assignable to type 'B'.
          Property 'b' is missing in type 'A' but required in type 'B'.

T_in_Y应该是T_in_X的扩展名

为什么要检查基类静态方法的参数应可分配给子类方法参数的类型,而不是相反?

0 个答案:

没有答案