[英]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.