node.js - 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 中获取可能的值的正确方法是什么?
谢谢米科
解决方案
推荐阅读
- ios - iOS 13 UISearchBar 外观和行为
- python - 在 python 中将 URL 参数传递给 webapp2.RequestHandler 会导致“无”
- powerbi - PowerBI 启用折叠
- angular - 如何修复在 Angular 中打开新选项卡时出现 404 Not Found 错误
- c++ - 如何从参数包构造 std::tuple 引用?
- ios - 无法在 Alert() 上单击确定
- postgresql - 在 postgres 中使用连接运算符更新 jsonb 字段
- java - Spring AMQP - Jackson2JsonMessageConverter 设置 _TypeId_ 自 2.1 版以来使用接口而不是具体类型
- visual-studio-code - 如何显示 VSCode 中安装的所有非主题扩展?
- c - 无法找出为什么我的程序没有做它应该做的事情