[英]Why is it possible to have both numeric and string index signatures for an interface in TypeScript?
[英]TypeScript Index Signatures with Interface Types
我有一个接口和一个 class:
interface Widget {
widgetStuff(): void;
}
class Foo implements Widget {
widgetStuff(): void {
}
}
我想跟踪另一个 class 中的所有Widget
,索引签名似乎是最简单的方法:
class WidgetCatalog {
private readonly mapping: { [key: string]: Widget };
constructor() {
this.mapping = {
Foo // <= Error here
}
}
}
我收到此错误: error TS2322: Type 'typeof Foo' is not assignable to type 'Widget'. Property 'widgetStuff' is missing in type 'typeof Foo'.
error TS2322: Type 'typeof Foo' is not assignable to type 'Widget'. Property 'widgetStuff' is missing in type 'typeof Foo'.
我不确定我在这里缺少什么,因为它似乎是一个非常简单的实现。 我是否需要以不同方式指定索引签名中的值类型?
@jcalz 为我指明了正确的方向。 此版本有效:
interface Widget {
widgetStuff(): void;
}
class Foo implements Widget {
widgetStuff(): void {
}
}
class WidgetCatalog {
// Change to mapping of Widget constructors
private readonly mapping: { [key: string]: new(...args) => Widget };
constructor() {
this.mapping = {
Foo
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.