Home > OS >  Derive the type of an array in Typescript
Derive the type of an array in Typescript

Time:12-21

I have a type that's defined in a third party library. Let's say its shape is:

type Foo = {
  id: string
  results: Array<{ bar: string }>
}

Is there a way to derive the type { bar: string }?

I'd like to use it like so:

type Baz = /* derived type */

const baz: Baz = { bar: 'abc' }

I was looking at utility types... but couldn't figure out how to target that part of the type definition.

CodePudding user response:

Arrays indexed by number give you the member type of the array, since arrays are indexed by integers.

type Foo = {
  id: string
  results: Array<{ bar: string }>
}

type Baz = Foo['results'][number]
const baz: Baz = { bar: 'abc' }

Playground

CodePudding user response:

Got some help from a TS wizard. This is a working solution:

type Foo = {
  id: string
  results: Array<{bar: string}>
}

type ElementsOf<T extends unknown[]> = T extends ReadonlyArray<infer E> ? E : never;

// type Baz = { bar: string; } 
type Baz = ElementsOf<Foo["results"]>;

Would love if someone could help explain the ternary though.

  • Related