MediumConcept

What are generics in TypeScript?

Technology:
TypeScript
Experience:
Junior,
Mid-level

Quick answer

Generics are type parameters: they let a function, class or type work with many types while keeping the relationship between inputs and outputs, instead of falling back to any.

Detailed explanation

identity<T>(value: T): T returns the same type it received. Without T you would write any and lose that link. Constraints (T extends { id: string }) describe the minimum shape. Several parameters (K, V) model maps and API wrappers.

Common interview follow-ups: default parameters (T = string), keyof T for safe property access, and why Array<T> and T[] are the same. Prefer inference (wrap(user)) over forcing wrap<User>(user) at every call site.

Example

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

first(["a", "b"]);          // string | undefined
first<number>([1, 2, 3]);   // number | undefined
  • TypeScriptEasy

    What is TypeScript and why do we use it?

    TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It catches type errors in the editor and at build time, and it documents the shape of data for the next person who reads the code.

    Intern 路 Junior 路 Types & Type System
  • TypeScriptMedium

    What are utility types in TypeScript like Partial, Pick and Omit?

    Utility types are built-in helpers that transform an existing type: Partial makes every field optional, Required the opposite, Pick keeps a set of keys, Omit removes them, and Record builds a key/value map.

    Junior 路 Mid-level 路 Types & Type System
  • TypeScriptMedium

    What is type narrowing in TypeScript?

    Narrowing is when TypeScript shrinks a wide type (such as a union) to a more specific type after a runtime check like typeof, instanceof, in, or a custom type guard.

    Mid-level 路 Senior 路 Types & Type System