Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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}"`)
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda