【问题标题】:Using Class Types in Generics在泛型中使用类类型
【发布时间】:2021-07-12 22:00:47
【问题描述】:

让我们看看这里的例子: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics

我需要做的就是在实例化之前调用一个静态方法,所以让我们修改示例如下:

class BeeKeeper {
    hasMask: boolean = true;
}

class ZooKeeper {
    nametag: string = "Mikle";
}

class Animal {
    static beforeInit() {
        console.log('do something here');
    };

    numLegs: number = 4;
}

class Bee extends Animal {
    static beforeInstantiate() {
        console.log('do some bee stuff here');
    };
    keeper: BeeKeeper = new BeeKeeper();
}

class Lion extends Animal {
    static beforeInstantiate() {
        console.log('do some lion stuff here');
    };
    keeper: ZooKeeper = new ZooKeeper();
}

function createInstance<A extends Animal>(c: new () => A): A {
    c.beforeInstantiate(); // TS2339: Property 'beforeInit' does not exist on type 'new () => A'.
    return new c();
}

createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;

我所做的只是在Animal 类中添加一个static 方法,并在实例化之前在createInstance 函数中调用它,我得到了以下错误: TS2339: Property 'beforeInit' does not exist on type 'new () =&gt; A'.

我应该如何修改c 的类型以使打字稿知道静态函数?

【问题讨论】:

  • 假设你有一个错字并且静态方法在基础和派生中是相同的:c: typeof Animal &amp; (new () =&gt; A)

标签: typescript typescript-generics


【解决方案1】:

您可以像这样使c 上的类型更具体:

c: (new () => A) & { beforeInstantiate: () => void }

或者像这样:

c: { new (): A, beforeInstantiate: () => void }

这些类型都表示c 必须是A 的构造函数,并且c 还必须具有静态beforeInstantiate 属性。

Playground link

顺便说一下,您的示例在 Animal 中使用 beforeInit,但在其他示例中使用 beforeInstantiate。您可能希望使它们相同。

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多