Class 类构造函数和接口
如何正确地键入实现接口的类 示例代码:Class 类构造函数和接口,class,typescript,interface,Class,Typescript,Interface,如何正确地键入实现接口的类 示例代码: interface IPlugin{ name:string; } class SomePlugin implements IPlugin{ name; constructor(){ this.name = 'Sam'; } } const arrayOfClass:IPlugin = [SomePlugin]; // Ther error : /* Type 'typeof SomePlugin[]' is not assig
interface IPlugin{
name:string;
}
class SomePlugin implements IPlugin{
name;
constructor(){
this.name = 'Sam';
}
}
const arrayOfClass:IPlugin = [SomePlugin];
// Ther error :
/*
Type 'typeof SomePlugin[]' is not assignable to type 'IPlugin'.
Property 'name' is missing in type 'typeof SomePlugin[]'.
*/
我应该怎么做呢?创建一个接口,描述将实例化实现
IPlugin
的对象的对象。您可以通过使用新签名来执行此操作:
interface IPluginConstructor {
new(...args: any[]): IPlugin;
}
现在键入arrayOfClass
作为IPluginConstructor
s的数组:
const arrayOfClass: IPluginConstructor[] = [SomePlugin];
注意类型中的[]
。问题中没有这一点
旁注
如果仔细观察,name
的类型是SomePlugin
中的any
。。。它被设置为any
,因为该类型被隐式地键入为any
,并且string
可分配给any
。这意味着编译以下代码:
const s = new SomePlugin();
const num: number = s.name; // this compiles... sad! :(
您应该显式地键入
class SomePlugin implements IPlugin {
name: string;
constructor() {
this.name = 'Sam';
}
}
class SomePlugin implements IPlugin {
name = 'Sam';
}
…或含蓄地
class SomePlugin implements IPlugin {
name: string;
constructor() {
this.name = 'Sam';
}
}
class SomePlugin implements IPlugin {
name = 'Sam';
}
我建议您启用
noImplicitAny
编译器标志,以帮助将来捕获此类错误。创建一个接口,描述将实例化实现IPlugin
的对象的对象。您可以通过使用新签名来执行此操作:
interface IPluginConstructor {
new(...args: any[]): IPlugin;
}
现在键入arrayOfClass
作为IPluginConstructor
s的数组:
const arrayOfClass: IPluginConstructor[] = [SomePlugin];
注意类型中的[]
。问题中没有这一点
旁注
如果仔细观察,name
的类型是SomePlugin
中的any
。。。它被设置为any
,因为该类型被隐式地键入为any
,并且string
可分配给any
。这意味着编译以下代码:
const s = new SomePlugin();
const num: number = s.name; // this compiles... sad! :(
您应该显式地键入
class SomePlugin implements IPlugin {
name: string;
constructor() {
this.name = 'Sam';
}
}
class SomePlugin implements IPlugin {
name = 'Sam';
}
…或含蓄地
class SomePlugin implements IPlugin {
name: string;
constructor() {
this.name = 'Sam';
}
}
class SomePlugin implements IPlugin {
name = 'Sam';
}
我建议您启用
noImplicitAny
编译器标志,以帮助将来发现此类错误。香蕉是水果,但一盒香蕉不是水果。这里也是一样:SomePlugin是IPlugin,但SomePlugin数组不是IPlugin。因此,这段代码没有多大意义,但在不知道您实际想要实现什么的情况下,很难给出建议。事实上,它甚至比这更糟糕。您没有香蕉弓,但有一个包含用于种植香蕉的配方的盒子,即一个包含SomePlugin类型的数组。尝试创建一个实现IPluginA的类构造函数数组香蕉是水果,但一盒香蕉不是水果。这里也是一样:SomePlugin是IPlugin,但SomePlugin数组不是IPlugin。因此,这段代码没有多大意义,但在不知道您实际想要实现什么的情况下,很难给出建议。事实上,它甚至比这更糟糕。你没有香蕉弓,但有一个盒子,里面有种植香蕉的配方,即一个数组,其中包含SomePlugin类型。尝试创建一个实现IPlugin的类构造函数数组