我不知道如何阐明我要做的事情,所以很难找到具体的答案,但这里是。
如果我有像这样的带有单个对象的简单文件
typeOne.ts
export const types = {
name: 'blah'
...
}
typeTwo.ts
export const types = {
name: 'blehh'
...
}
我在某个地方有另一个类,它将取哪个类的名称来拉入并执行功能
public getTypes(typeName: string) {
return {typeName from typeOne ... typeTwo ...} // how to import here?
}
所以我可以称之为
const theTypes = this.getTypes('typeOne');
或
const theTypes = this.getTypes('typeTwo');
这就是我试图实现的,这样getTypes
函数就是通用的,不需要单独定义每个函数?
感谢
别名导入
import { types as typeOne } from "./typeOne"
import { types as typeTwo } from "./typeTwo"
import { Type } from "./Type"
const allTypes = { typeOne, typeTwo }
const getTypes = (typeName: keyof typeof allTypes): Type =>
allTypes[typeName]
// Type.ts
export interface Type {
name: string
}
getTypes
函数的另一种方法可能看起来像。。。
const getTypes = (typeName: string): Type => {
switch (typeName) {
case "typeOne" :
return typeOne
case "typeTwo" :
return typeTwo
default :
throw new Error(`Unknown type "${typeName}"`)
}
}