Glossary

Generics

Generics are a mechanism for parameterised types: write a class or function once that works with any type while preserving type safety. The compiler checks types at build time, not at runtime.

Example (TypeScript)

function firstItem(arr: T[]): T | null {
  return arr.length ? arr[0] : null;
}

const n = firstItem([1, 2, 3]); // number
const s = firstItem(['a', 'b']); // string

In PHP

PHP has no built-in generics, but PHPStan/Psalm support them via @template annotations and doc blocks. They are checked statically, not at runtime.

/** @template T */
class Collection {
  /** @param T $item */
  public function add($item): void { ... }
}

Where used

Collections, repositories, Result types, any container. Java, C#, TypeScript, and Go (since 1.18) have built-in generics.