You want one function, last, that takes the last item from any array: numbers, text, booleans. If the parameter is typed number[], an array of text is refused. If it's typed any[], everything gets in, but the result's type becomes any too, so TypeScript no longer knows what type comes out.
A generic is the middle way: one function (or one type) that works for many types without losing the type information. You do it with a type parameter, usually called T. A type parameter is like a variable, except it holds a type, and that type is decided each time the function is called. Think of a cloakroom: the attendant doesn't care whether you leave a helmet or an umbrella, but what you pick up is always the very thing you left. The cloakroom is the generic function. The thing you leave is the argument, with its type T, and the thing you pick up is the return value, with the same type T.
Why not just use any
We want a function that takes the last item of any array. The easiest way is any:
function lastAny(arr: any[]): any {
return arr[arr.length - 1];
}
const result = lastAny([1, 2, 3]); // result: any
result.toUpperCase(); // TypeScript says nothing
When the program runs, the last line stops with an error:
TypeError: result.toUpperCase is not a function
any disables checking. result is really the number 3, and numbers have no .toUpperCase(), yet TypeScript reports no error. The error only appears when the program runs, while the whole point of TypeScript is to catch errors like this before the program runs.
T follows the argument
This is the generic version of the same function:
function last<T>(arr: T[]): T {
return arr[arr.length - 1];
}
const a = last([1, 2, 3]); // T = number, a: number, value 3
const b = last(["a", "b"]); // T = string, b: string, value "b"
const c = last([true, false]); // T = boolean, c: boolean, value false
<T>after the function name creates a type parameter calledT. The angle brackets< >mark a generic. The nameTis just a habit, and you can have more than one type parameter, like<K, V>.arr: T[]means "an array of T", and: Tafter the parentheses means the function returns one T.- You don't have to write T. TypeScript guesses it from the argument. This is called inference.
arr.length - 1is the last index, because indexes start at 0.[1, 2, 3]has 3 items, so its last index is 2.
| Call | T | Result type | Value |
|---|---|---|---|
last([1, 2, 3]) |
number |
number |
3 |
last(["a", "b"]) |
string |
string |
"b" |
last([1, "a"]) |
string | number |
string | number |
"a" |
So a is a number, and b is a string. Because the types are exact, b.toUpperCase() is allowed, while a.toUpperCase() is refused before it runs:
error TS2339: Property 'toUpperCase' does not exist on type 'number'.
You can also write T yourself: last<string>(["a", "b"]). If the contents don't fit, as in last<string>([1, 2, 3]), each number is refused with Type 'number' is not assignable to type 'string'. (ts(2322)).
Limiting T with extends
Sometimes your function needs something from a value of type T. The function getLength below needs .length:
function getLength<T extends { length: number }>(value: T): number {
return value.length;
}
getLength("word"); // 4
getLength([1, 2, 3]); // 3
getLength(123); // error
The line getLength(123) is refused:
error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.
T extends { length: number }means "T can be any type, as long as it has alengththat is a number". This limit is called a constraint. Hereextendsdoesn't mean inherits, as it does for an interface: it is a condition T must meet. Strings and arrays have alength, numbers don't.- Without
extends, the linereturn value.lengthitself gets the error:Property 'length' does not exist on type 'T'.T could be any type, numbers included, so TypeScript can't be sure there's alength.
Generic types
Not just functions. Interfaces and type aliases can have type parameters too:
interface ApiResponse<T> {
data: T;
status: number;
}
const res: ApiResponse<string[]> = { data: ["Coffee", "Tea"], status: 200 };
ApiResponse<string[]> fills T with string[], so data must be an array of strings. The shape of ApiResponse is the same for every endpoint (an address on a server that sends data), only the type of data changes. You've actually used generic types many times already: string[] is the same as Array<string>.
⚠️ The any shortcut, and an index that's off by one
- Using
anyto make it easy. TypeScript accepts the code, but the error moves to run time. Use<T>so the result type stays exact. - Forgetting
<T>after the function name.function last(arr: T[]): Tis refused withCannot find name 'T'.T has to be created first, inside< >. - The last index off by one.
arr[arr.length]is one place past the last item, so it is alwaysundefined. The last index isarr.length - 1. - An empty array.
last([])returnsundefined, even though its type isT. In the exercise, the function uses: T, and the array sent always has items. In real code, writefunction last<T>(arr: T[]): T | undefined { return arr.at(-1); }(at(-1)takes the last item). WithnoUncheckedIndexedAccess(a setting thatnpx tsc --initturns on), the: Tversion is rejected:Type 'T | undefined' is not assignable to type 'T'.ts(2322). - Returning the whole array.
return arrreturns[1, 2, 3], not3, and TypeScript refuses it:Type 'T[]' is not assignable to type 'T'.
TL;DR: A generic uses a type parameter like <T> (like a variable that holds a type), so one function works for many types, and TypeScript still knows the result's type. function last<T>(arr: T[]): T returns the last item of the array (arr[arr.length - 1]), and TypeScript guesses T from the argument: last([1, 2, 3]) is a number, last(["a", "b"]) is a string. Unlike with any, a mistake like .toUpperCase() on a number is caught before the program runs. Limit T with extends: when getLength uses T extends { length: number } (T must have a length), TypeScript refuses getLength(123), because a number has no length. Interfaces can be generic too, like ApiResponse<T>, where T decides the type of the property data.
⚡ any passes, and the error moves to run time
Write:
function lastAny(arr: any[]): any {
return arr[arr.length - 1];
}
const result = lastAny([1, 2, 3]);
result.toUpperCase();
Guess first: does TypeScript report an error on the last line?
No. any disables checking, so the error only appears while the program runs: TypeError: result.toUpperCase is not a function.
Meaning: result is really the number 3, but because its type is any, TypeScript doesn't know that result is a number.
⚡ T follows the argument
Write:
function last<T>(arr: T[]): T {
return arr[arr.length - 1];
}
const a = last([1, 2, 3]); // a: number
const b = last(["a", "b"]); // b: string
Meaning: <T> makes a type parameter, a kind of variable that holds a type. A function with a type parameter is called a generic. TypeScript guesses T from the argument, so a is a number, and a.toUpperCase() is rejected before running. arr.length - 1 is the last index, because indexes start at 0.
⚡ Limit T with extends
Write:
function getLength<T extends { length: number }>(value: T): number {
return value.length;
}
getLength("word"); // 4
getLength(123); // error
Meaning: T extends { length: number } means T can be any type, as long as it has a length. This limit is called a constraint. Strings and arrays have one, numbers don't, so getLength(123) is rejected.