Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!