Search code examples
typescripttypescript-typings

How to add variable as key name in typescript interface?


This is how my object would look like. This is very small version of object and I have to deal with large object.

const obj = {
    name: 'name_key',
    details: 'details_key',
    profile: 'profile_key',
}

So, if we want to use value of this object in another object then we can use it like:

const newObj = {
    [obj.name]: 'some_value',
    [obj.details]: 'some_value',
    [obj.profile]: 'some_value',
}

So, here newObj would become like:

newObj = {
    'name_key': 'some_value',
    'details_key': 'some_value',
    'profile_key': 'some_value',
}

The same way I want to use it with interface but I'm unable to do so.

interface User {
    [obj.name]: string;
    [obj.details]: DetailsInterface;
    [obj.profile]: ProfileInterface;
}

I have tried this approach but it throws error like "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type." Here DetailsInterface and ProfileInterface are also interface.

I have tried union approach but it doesn't work as all the keys have different types of interface or data type.


Solution

  • I found solution. The object that we have defined is mutable. So if we use like

    const obj = {
        name: 'name_key',
        details: 'details_key',
        profile: 'profile_key',
    } as const;
    

    it becomes unmutable and all the fileds have string value. Now we can use this object fiels as computing keys name in interface as shown below

    interface User {
        [obj.name]: string;
        [obj.details]: DetailsInterface;
        [obj.profile]: ProfileInterface;
    }
    

    So finally interface User becomes like

    interface User {
        name_key: string;
        details_key: DetailsInterface;
        profile_key: ProfileInterface;
    }