Interfaces, classes and generics

Describe object shapes with interface and type, write classes, and reuse code for any type with generics.

Runs in Zerethon IDE · TypeScript 7 Official TypeScript documentation ↗
main.ts
interface User {
  readonly id: number;
  name: string;
  email?: string;
}

class Stack<T> {
  private items: T[] = [];
  push(item: T): void {
    this.items.push(item);
  }
  pop(): T | undefined {
    return this.items.pop();
  }
  get size(): number {
    return this.items.length;
  }
}

function first<T>(items: T[]): T | undefined {
  return items[0];
}

const ada: User = { id: 1, name: 'Ada' };
const stack = new Stack<User>();
stack.push(ada);
console.log(stack.size, stack.pop()?.name, stack.pop());
console.log(first([3, 1, 2]), first<string>([]));

Output

1 Ada undefined
3 undefined
  • interface and type both describe object shapes; type can also name unions.
  • Types are structural: any object with the right fields fits, whatever its class.
  • A generic <T> keeps the caller's type: first([3, 1, 2]) returns number | undefined.