1

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": ""
    },
    ...
]
3
  • From which keys are you supposed to infer the union type from? Commented Feb 8, 2023 at 0:06
  • @Terry I'm not sure what you mean. Could you elaborate, or perhaps use simpler language? I'm not very advanced at Typescript yet. Commented Feb 8, 2023 at 0:15
  • In your original question you are trying to infer a union type from different keys "foo1" and "foo2", but I can see you've updated your question. With the same key "foo" it's much easier and simpler to get the union type you want. Commented Feb 8, 2023 at 0:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.