RUN

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.

main.ts

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

Open the full TypeScript online compiler →