TypeScript Generics
Write one function that keeps the type of whatever it receives.
On this page
TypeScript functions and arrays.
- Write one function that keeps the type of whatever it receives.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A generic function takes a type parameter, written <T>, so it can work with many types while still being checked. first<T> returns the first element of a T[] and has the return type T | undefined.
TypeScript usually infers T from the argument, so first([10, 20, 30]) is a number | undefined. When there is nothing to infer from, such as an empty array, you can pass the type yourself with first<number>([]).
Code example
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([10, 20, 30]);
const s = first(["a", "b"]);
const none = first<number>([]);
console.log(n, s, none);10 a undefined
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
function first<T>(items: T[]): T | undefined { return items[0];} const n = first([10, 20, 30]);const s = first(["a", "b"]);const none = first<number>([]);console.log(n, s, none);Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| T is a placeholder filled in at each call. | — | — | |
| T is inferred as number, so n is 10. | n = 10 | — | |
| T is inferred as string, so s is "a". | s = "a" | — | |
| An empty array has no first element, so the result is undefined. | none = undefined | — | |
| console.log separates its arguments with a space. | none = undefined | 10 a undefined |
Behind the scenes
How TypeScript processes this code
TypeScript checks types and emits JavaScript. Type annotations are removed before execution.
Cost and common mistakes
O(1) time and space per call.
- Indexing an empty array returns undefined at runtime, which is why the return type includes undefined.
- Generics are erased at compile time; you cannot test T at runtime.
Try it yourself
Write last<T>(items: T[]) that returns the final element.
Reveal answer and reasoning
return items[items.length - 1]; the return type is again T | undefined.