TypeScript Generics
A generic function is a function that names a placeholder type. The compiler fills the placeholder with a real type at each call.
A generic identity function
identity returns the value it receives. The type of the value becomes T at each call.
function identity<T>(value: T): T {
return value;
}
console.log(identity("hello"));
console.log(identity(42));An explicit type argument
A type argument names T directly at the call. The argument must match that type.
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("hello"));
console.log(identity<number>(7));A mismatched type argument
The call names number as T. The string argument does not match the named type.
function identity<T>(value: T): T {
return value;
}
console.log(identity<number>("five"));A generic array function
first reads the first item of an array. The array item type becomes T at each call.
function first<T>(items: T[]): T {
return items[0];
}
console.log(first([10, 20, 30]));
console.log(first(["red", "blue"]));Example
function identity<T>(value: T): T {
return value;
}
function first<T>(items: T[]): T {
return items[0];
}
console.log(identity("done"));
console.log(identity(true));
console.log(first([5, 9, 2]));
console.log(first(["a", "b", "c"]));Key points
- The letter T is a common name for a placeholder type.
- The placeholder is written inside angle brackets after the function name.
- The compiler infers T from the argument when no type argument is given.
- A type argument can be written in angle brackets at the call.
- One generic function can work with many types without copies.
In this example, identity runs with a string and then with a boolean. Each call fills T with a different type. first then reads the first item from a number array and from a string array.
Note
TypeScript erases generic types when it emits JavaScript.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does T stand for in a generic function?