gpt4 book ai didi

TypeScript 类型数组

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:13 24 4
gpt4 key购买 nike

我有以下界面:

export interface FooInterface {
barAction(x: any) : void;
}

然后我来实现它:

class FooImplA implements FooInterface {
barAction(x: any) : void {};
}

class FooImplB implements FooInterface {
barAction(x: any) : void {};
}

class FooImplB implements FooInterface {
barAction(x: any) : void {};
}

现在我想要一个类型 FooImplAFooImplB 的数组(不是实例)。

显然,这是可行的:

  let typeArray = [FooImplA, FooImplB];

但我希望它是强类型的。以下是我的想法,但行不通:

  let typeArray: Array< (typeof FooInterface) > = [FooImplA, FooImplB];

最佳答案

使用您的代码:

interface FooInterface {
barAction(x: any) : void;
}

class FooImplA implements FooInterface {
barAction(x: any) : void {};
}

class FooImplB implements FooInterface {
barAction(x: any) : void {};
}

let typeArray = [FooImplA, FooImplB];

typeArray变量的类型是:typeof FooImplA[],可以看到in playground将鼠标悬停在 typeArray 上。
原因是编译器推断数组本身的类型,而不需要明确地告诉它。

如果你确实想在代码中包含它,那么你可以这样做:

type FooImplConstructor = { new (): FooInterface };

let typeArray: FooImplConstructor[] = [FooImplA, FooImplB];
// or
let typeArray = [FooImplA, FooImplB] as FooImplConstructor[];

关于TypeScript 类型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40590487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com