[SOLVED] 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.


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]

Answered By – DaSch

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *