Array element type
- TypeScript course
- Intermediate
- Lesson 42/89
- 4 min
Learn to extract the element type of an array with infer.
Array element type
The pattern (infer E)[] extracts the element type of an array as E. The pattern T extends (infer E)[] ? E : never gives the element type when T is an array. This is useful in generic helpers that need to know an array's element type.
type Eleman<T> =
T extends (infer E)[] ? E : never;
type R = Eleman<string[]>;
// R: stringWhy the parentheses matter
In (infer E)[] the parentheses are mandatory. Writing infer E[] tries to declare an array of element types named E and is a syntax error. The parentheses say: first infer E, then require the type to be an array of E.
Practice Extract the array element type
Write the conditional type Eleman<T> as T extends (infer E)[] ? E : never. Define type Sonuc as Eleman<string[]>. Define variable a with type Sonuc and assign "elma". Print a with console.log.
Starter code
// Eleman<T> koşullu türünü tanımla
// T bir dizi ise eleman türünü çıkar, değilse never
// Sonuc türünü Eleman<string[]> olarak tanımla
// a değişkenini Sonuc türünde tanımla, "elma" ata
// a'yı console.log ile yazdırSample solution
type Eleman<T> = T extends (infer E)[] ? E : never;
type Sonuc = Eleman<string[]>;
const a: Sonuc = "elma";
console.log(a);Expected output
elma
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Eleman<number[]> produce?
type Eleman<T> = T extends (infer E)[] ? E : never;
type R = Eleman<number[]>;- number Correct answer
- never
- any[]
- number[]
Explanation: Since T is an array, the pattern matches and E becomes the element type, number. The true branch returns E. number[] is the matched type itself; never is the wrong branch; any[] is not an inference result.
2 Add the array brackets
type Eleman<T> =
T extends (infer E)____ ? E : never;
type Eleman<T> =
T extends (infer E)[] ? E : never;
Explanation: After inferring the element type you add [] to require the array condition. {} is an object type; [T] forms a tuple; E alone does not form the array condition.
3 Array infer parts
| Term | Meaning |
|---|---|
(infer E) |
Inferred element type |
(infer E)[] |
Array match pattern |
? E |
True branch: the element type |
Eleman<string[]> |
Usage example |