harbar20
harbar20

Reputation: 33

Creating type based on object values in an array JSON in TypeScript

I have a JSON file that has a format something like this:

[
    {
        "foo1": "bar1",
        "something": "",
        "else": ""
    },
    {
        "foo2": "bar2",
        "something": "",
        "else": ""
    },
    ...
]

and I want to create a type with only the "bar" values i.e. the values of the foos of all the objects in the list.

I want to create a type that produces the following:

type bars = "bar1" | "bar2" | "bar3" | //...

but I have no idea where to even start. How do I traverse through that list and only return the values, then store them in a type?

Edit: I made a mistake. The JSON file actually looks more like this:

[
    {
        "foo": "bar1",
        "something": "",
        "else": ""
    },
    {
        "foo": "bar2",
        "something": "",
        "else": ""
    },
    ...
]

Upvotes: 1

Views: 41

Answers (1)

Terry
Terry

Reputation: 66103

If you can define your data as const then you can easily infer the union type of the foo key using mapped types:

const data = [
    {
        "foo": "bar1",
        "something": "",
        "else": ""
    },
    {
        "foo": "bar2",
        "something": "",
        "else": ""
    },
] as const;

// Expected: type bars = "bar1" | "bar2"
type bars = typeof data[number]['foo'];

See example on TypeScript playground.

Upvotes: 1

Related Questions