Home > other >  How to add variable as key name in typescript interface?
How to add variable as key name in typescript interface?

Time:01-04

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.

CodePudding user response:

you can't create a strong-typed interface for something that is defined at runtime, that's not how TypeScript works.

What you could do instead is having a broader interface/type definition that will match with that obj, like this:

type User = Record<string, any>

But if obj is statically defined, you can generate a interface from it, like so:

code

I'm unsure if this was what you were looking for tho.

CodePudding user response:

I found solution. The object that we have defines 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;
}
  • Related