具有接口类型的TypeScript索引签名

问题描述 投票:0回答:1

我有一个接口和一个类:

interface Widget {
  widgetStuff(): void;
}

class Foo implements Widget {
  widgetStuff(): void {
  }
}

我想跟踪另一个类中的所有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'.

我不确定我在这里缺少什么,因为这似乎是一个非常简单的实现。我是否需要以其他方式在索引签名中指定值类型?

typescript
1个回答
0
投票

@@ 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
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.