Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda