Generics in TypeScript
Write one function that works with any type, safely. Press Run to try it, then change the code and run it again.
function firstItem<T>(items: T[]): T | undefined {
return items[0];
}
const n = firstItem([10, 20, 30]); // number | undefined
const s = firstItem(['a', 'b']); // string | undefined
console.log(n, s);
class Stack<T> {
private items: T[] = [];
push(item: T) { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
get size() { return this.items.length; }
}
const stack = new Stack<number>();
stack.push(1);
stack.push(2);
console.log(stack.pop(), stack.size);
Output
Press Run to see the output.
More TypeScript examples
- Hello, World · Print a line of text with a typed variable.
- Interfaces and objects · Describe the shape of an object and use it in a function.
- Union types and narrowing · Handle values that can be one of several types.
- Catch a type error · See how TypeScript stops a bug before the code runs.
- Async and await · Wait for promises with typed results.