Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 类型的类型脚本数组_Typescript - Fatal编程技术网

Typescript 类型的类型脚本数组

Typescript 类型的类型脚本数组,typescript,Typescript,我有以下界面: 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

我有以下界面:

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 {};
}
现在我想要一个类型的数组
FooImplA
FooImplB
(不是实例)

显然,这是可行的:

  let typeArray = [FooImplA, FooImplB];
但是我想要强类型的。以下是我的想法,但不起作用:

  let typeArray: Array< (typeof FooInterface) > = [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[]
,将鼠标悬停在
typeArray
上可以看到这一点 原因是编译器推断数组本身的类型,而不需要显式地告诉它

如果您确实希望将其包含在代码中,则可以执行以下操作:

type FooImplConstructor = { new (): FooInterface };

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

我可能误解了这个问题,但是
让typeArray:FooInterface[]=…
不是你想要的吗?让typeArray:FooInterface[]只在你有
=[new FooImplA(),new FooImplB()]
哦,对了-这些是对类型的引用,而不是实例。我注意到在对Angular 2编程时,我们最终使用了他们的接口“Type”:
导出接口类型扩展函数{new(…args:any[]):T;}
。这可能有一定的局限性,尽管它至少可以让您定义构造函数参数。