TypeScriptTypeScript18 min read

Generic Constraints

Restrict generics using constraints so you can safely access properties while keeping flexibility.

David Miller
January 9, 2026
0.7k15

Sometimes you want generics, but with rules.

    ## Example: must have length
    
    ```ts
    function logLength<T extends { length: number }>(val: T): T {
      console.log(val.length);
      return val;
    }
    
    logLength("hello");
    logLength([1, 2, 3]);
    // logLength(10); ❌
    ```
    
    ## With interfaces
    
    ```ts
    interface HasId {
      id: number;
    }
    
    function printId<T extends HasId>(obj: T) {
      console.log(obj.id);
    }
    ```
    
    ## Why constraints?
    So TypeScript knows what properties exist.
    
    ## Graph
    ```mermaid
    flowchart TD
      A[T] --> B{extends rule}
      B --> C[Allowed]
      B --> D[Rejected]
    ```
    
    ## Remember
    - Use extends to limit generics
    - Keeps flexibility with safety
    
#TypeScript#Intermediate#Generics