[英]How to import an object from another file using a variable name in typescript/javascript
I'm not sure how to articulate what I'm trying to do so it's hard to find specific answers, but here goes.我不确定如何表达我正在尝试做的事情,所以很难找到具体的答案,但这里有。
If I have simple files with individual objects like如果我有带有单个对象的简单文件,例如
typeOne.ts
export const types = {
name: 'blah'
...
}
typeTwo.ts
export const types = {
name: 'blehh'
...
}
I have another class somewhere that will take the name of which one to pull in and perform functions我在某处有另一个 class 将取哪个名称来拉入并执行功能
public getTypes(typeName: string) {
return {typeName from typeOne ... typeTwo ...} // how to import here?
}
And so I can call it basically所以我基本上可以称之为
const theTypes = this.getTypes('typeOne');
or或者
const theTypes = this.getTypes('typeTwo');
So that is what I'm trying to achieve so that the getTypes
function is generic and does not need to define each one individually?所以这就是我想要实现的,以便getTypes
function 是通用的,不需要单独定义每个?
Thanks谢谢
Alias your imports别名你的进口
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
}
An other approach to the getTypes
function might look like... getTypes
function 的另一种方法可能看起来像......
const getTypes = (typeName: string): Type => {
switch (typeName) {
case "typeOne" :
return typeOne
case "typeTwo" :
return typeTwo
default :
throw new Error(`Unknown type "${typeName}"`)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.