Search code examples
typescripttypescript-typings

How declare object that key of it have diffrent name but same type in typescript?


I need declare an object that have a lot of keys, I so tired if will define one by one.

like this:

type ReturnValue = {
   // here have a lot of keys, I want a simple way to declare.
   // May I do that?
   ['name'| 'phone' | ... ]: string;
}

I haven't tried, I don't know what to do.

It's best if will have a way to do.


Solution

  • You can use TypeScript's mapped types along with a union type to achieve this more concisely. Here's how you can declare your ReturnValue type using a mapped type:

    type Keys = 'name' | 'phone' | /* add more keys here */;
    
    type ReturnValue = {
      [K in Keys]: string;
    }
    
    

    This will create a type ReturnValue with keys specified in the Keys union type, and each key will have a value of type string. This approach allows you to avoid manually specifying each key one by one.