'Access typescript uniontype inside array type
I'm actually not event sure how to phrase the question correctly. From a code generator I get the following interface as an input for an API request:
interface foo {
bar: ('foo' | 'bar')[]
}
To access this I can create aliases like type xy = foo['bar']. But I actually have no idea how to get a type that includes the union inside an array. I want to have a type type union = 'foo' | 'bar' by referencing the interface.
I already tried to use index anotation like type union = foo['bar'][string] or type union = foo['bar'][number] but that throws an error.
Solution 1:[1]
Well, actually the issue I had was a bit different and is missing in my example.
If you have
interface Foo {
bar?: ('foo' | 'bar')[]
}
Then type BarOrFoo = Foo['bar'][number]; // "bar" | "foo" will not work.
But instead the following works
type BarOrFoo = Exclude<Foo['bar'], undefined>[number]
Solution 2:[2]
You can do this by accessing the bar property via interface property access notation: foo["bar"], then access the item union by indexing with number to get the type of the items. Here is the full code:
interface foo {
bar: ('foo' | 'bar')[]
}
type FooBarItem = foo["bar"][number];
// ^? "bar" | "foo"
Solution 3:[3]
Update based on new information you presented:
Because the property is optional, you can use the type utility NonNullable<Type> to exclude null and undefined from its union. Then, you can use an indexed access type (number in this case to access elements in an array, which are indexed by number keys).
interface Foo {
bar?: ('foo' | 'bar')[];
}
type BarOrFoo = NonNullable<Foo['bar']>[number]; // "bar" | "foo"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DaSch |
| Solution 2 | sno2 |
| Solution 3 |
