Home > Mobile >  How to create a typescript union type with values from a JSON object
How to create a typescript union type with values from a JSON object

Time:09-23

Suppose I have this JSON object

[
  { "label": "The entire place", "value": "entire_place" },
  { "label": "A shared room", "value": "shared_room" },
  { "label": "A private room", "value": "private_room" },
]

Those represent the possible values of a dropdown menu. The label is what the user sees, and the value is what's stored in the database.

However, I also need to create a type as follows:

type Property = "entire_place" | "private_room" | "shared_room";

How can I do so without defining the data twice?

I don't want to change the type and JSON object every time I need to add a new possible values.

Any ideas how to do so? If it's not possible, what's a better alternative to store data (along their label) and use it for validation.

CodePudding user response:

First, you need to declare your array as a const, that way typescript generates the specific values rather than just string. Then you can use typeof and index the array with number and lastly value:

const data = [
    { label: 'The entire place', value: 'entire_place' },
    { label: 'A shared room', value: 'shared_room' },
    { label: 'A private room', value: 'private_room' },
] as const;

type Property = typeof data[number]['value'];

Declaring it as a const does mean you can't modify the array, which is a good thing. If you want to keep it entirely in sync with the array, I don't believe that's possible.

  • Related