网站搜索

TypeScript - 通过接口查找类


假设以下代码:

interface FirstInterface {}
interface SecondInterface {}
interface ThirdInterface {}

class TheClass {
  constructor(howdy: FirstInterface) {}
}

class Foo implements FirstInterface {}
class Bar implements SecondInterface {}
class Whatever implements ThirdInterface {}

[
  new Foo(),
  new Bar(),
  new Whatever()
].forEach(cls => {
  // How to find out which one of the three classes to use here?
  // if(cls instanceof FirstInterface) obviously doesn't work :(
  new TheClass(cls);
});

我想将适当的类注入到 TheClass,在这种情况下就是 Foo。

我知道接口在编译后会完全消失——但对此有什么解决办法吗?

原因:我的 DI 容器会自动注入依赖项,这些依赖项确实可以是接口。但在解析在构造函数中使用接口的类时,如果不知道至少接口的名称,我根本不知道应该使用哪个类。

答案#1

使用判别属性怎么样?像这样的东西

interface FirstInterface {kind: 'firstInterface'}
interface SecondInterface {kind: 'secondInterface'}
interface ThirdInterface {kind: 'thirdInterface'}

class Foo implements FirstInterface {}
class Bar implements SecondInterface {}
class Whatever implements ThirdInterface {}

[
  new Foo(),
  new Bar(),
  new Whatever()
].forEach(cls => {
  // How to find out which one of the three classes to use here?
  if(cls.kind === 'firstInterface') new TheClass(cls);
});

你可以在操作平台上看到一个工作示例

答案#2

我已经通过从接口切换到抽象类为自己解决了这个问题。你可以在这里找到我天真的依赖注入实现。