Typescript: Infer type from an array

Viewed 35

Let's say I have following type:

type TestType = { abc: string }[];

I would like to extract { abc: string } part, but don't know how.

I tried to get first element from tuple, but no luck:

type Head<T extends any[]> = T extends [a: infer A, ...args: any[]] ? A : never;

that approach works for [{ abc: string }] but not for { abc: string }[] although types are the same (I guess !?).

1 Answers

Given type TestType = { abc: string }[];, you can do:

type ExtractedType = TestType[number]; which is equal to { abc: string }

Moreover, if you need to extract the type of the property abc, you could then do type Foo = ExtractedType["abc"].

Related