0

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.

3 Answers 3

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"

TypeScript Playground Link

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

Comments

0

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]

1 Comment

New question information belongs in the question content.
-1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.