简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM