首页 > 解决方案 > Typescript - 动态类类型

问题描述

我正在尝试在 Typescript 中构建一种模型工厂。我从 API 调用接收一个字符串参数,我想根据接收到的值创建一个新对象。

在这里,您可以找到我想要完成的简单示例:

/classes/ClassA.ts

export class ClassA {
  doSomething() {
    console.log("ClassA");
  }
}

/classes/ClassB.ts

export class ClassB {
  doSomething() {
    console.log("ClassB");
  }
}

/classes/index.ts

import { ClassA } from './ClassA';
import { ClassB } from './ClassB';
export { ClassA, ClassB }

现在,我想导入从 index.ts 导出的所有类(这个文件将在创建新类时自动更新)并根据变量值在类上运行 doSomething() :

/index.ts

import * as Classes from './classes';

const className: string = "ClassA";
new Classes[className]().doSomething()

在visualStudioCode中我没有得到任何错误,但在编译时我得到:

error TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'typeof import("/testApp/src/tmp/classes/index")'.

即使将className更改为“any”也会得到相同的结果。

如果我删除 className 类型

const className = "ClassA";

它可以正常工作,但我无法继续朝这个方向前进,因为接收到的值被“键入”为字符串。我知道在实例化代码之前加上

// @ts-ignore

它有效,但我想避免这种“技巧”那么,键入 className 从导入的 ts 中获取可能的值的正确方法是什么?

谢谢米科

标签: node.jstypescriptts-node

解决方案


推荐阅读