Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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}"`)
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading