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

206
Visualizações
TypeScript object type casting, when the two objects differ by key name(s)

This might have been asked before, but I have a situation where I have an object type which my backend expects like so:

type TagTypeThatMyBackendWants = {
    id: string;
    name: string;
}

It consist of two string type keys, the key names being id and name. I get these type of Tag-objects from my backend and my backend also expects objects like these back. Now, the problem is that I am using a library that handles these tags, but the library expects the objects to look like this:

type TagTypeThatALibraryWants = {
    id: string;
    text: string;
}

So it is basically the same object, but instead of a name key with a type of string, the library expects a text key with a type of string. I kind of already solved this by doing some custom mapping back and forth, but this raised the question if there is an "official" or a recommended way to do something like this - like casting from one object type to another, with the ability to tell TypeScript that the name-key "maps" to text-key and vice versa.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Don't overthink it:

function backendToLibrary(input: TagTypeThatMyBackendWants): TagTypeThatALibraryWants {
  return {
    id: input.id,
    text: input.name
  }
}

It's tempting to look at a problem like this, especially if you need to do it many times and think: perhaps there's an abstraction here.

But ultimately you know how properties map, so if you were to use/write a generic mapping utility, you would still need to configure this utility for each specific case, ultimately resulting in something that's more complex then if you literally just wrote it out for each case.

Unless I'm missing a use-case, I don't think there's a benefit to doing something more complicated.

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