Search code examples
typescripttypesinterfaceconvertersmapper

Custom Object Conversion in TypeScript


I am having trouble mapping one of the object into another type of the object.

Let's say I have a User and Programmer interface as follows.

interface User {
    name: string;
    age: number;
    languages: string[]
}

interface Programmer {
    name: string;
    age: number;
    languages: string;
}

And I would like to covert as follows.

const user_john: User = {
    name: "john",
    age:20,
    languages: ["React", "Angular", "Vue"]
}
const programmer_john = {
    name: "john",
    age:20,
    languages: "React,Angular,Vue"
}

Here is what I wish to do.

let programmer: Programmer = {} as Programmer;

Object.keys(user_john).map((key: string) => {
    programmer[key] = user_john[key]
})

But it gives me error and says I need to put the any, or @ts-ignore. which I do not want to do. And this is just simplified version of my code. actual code has more keys to each interfaces which makes me not want to map it manually one by one.

I believe I found the post talking about const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) => obj[key]; but I did not work or I am not sure how to use it correctly.

Can someone help me out for this issue please?


Solution

  • TypeScript often works best when you can create objects all at once in a single statement.

    You don't need to iterate over all the keys explicitly - you can use rest syntax to put all key-value pairs of the original object into the new object, and add a new property that joins the languages array.

    const programmer_john: Programmer = {
      ...user_john,
      languages: user_john.languages.join(',');
    };