Home > database >  Access typescript uniontype inside array type
Access typescript uniontype inside array type

Time:03-21

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.

CodePudding user response:

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"

TypeScript Playground Link

CodePudding user response:

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).

TS Playground

interface Foo {
  bar?: ('foo' | 'bar')[];
}

type BarOrFoo = NonNullable<Foo['bar']>[number]; // "bar" | "foo"

CodePudding user response:

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]
  • Related