Home > Net >  How to import an object from another file using a variable name in typescript/javascript
How to import an object from another file using a variable name in typescript/javascript

Time:02-04

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

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 ?

Thanks

CodePudding user response:

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...

const getTypes = (typeName: string): Type => {
  switch (typeName) {
    case "typeOne" :
      return typeOne
    case "typeTwo" :
      return typeTwo
    default :
      throw new Error(`Unknown type "${typeName}"`)
  }
}
  •  Tags:  
  • Related