Skip to content

Generics

Goal: Write reusable functions with type parameters.

Type parameters use angle brackets: function id<T>(x: T): T. No extends constraints on type parameters.

Example

function id<T>(value: T): T {
  return value
}

function first<T>(items: T[]): T? {
  if (items.length === 0) return null
  return items[0]
}

const n: number = id(42)
const s: string = id("ok")

Open in playground

Key takeaways

  • Generics monomorphize at compile time.
  • Use structural object types for bounds, not T extends U.
  • Type args can be inferred at call sites.

Next: Classes

Documentation