Course contentsShow
← TypeScript
Lesson 565 of 1,79613. GenericsFree lesson

Constraining to Primitives and Literals

Constrain type parameters to specific primitive types or literal unions for precise control.

Constraining to Primitives and Literals

What you'll learn: How to limit generic type parameters to specific primitive types or literal values for more controlled, predictable generic functions.

The Need for Precise Constraints

Sometimes you want a generic function that works with any string, number, or boolean—but only those types, not objects or arrays. Or you might want to accept only specific literal values, like "GET" | "POST" rather than any string. This is where constraining to primitives and literals becomes powerful.

Constraining to Primitives

You can use primitive types like string, number, or boolean as constraints:

function logAndReturn<T extends string>(value: T): T {
  console.log(value.toUpperCase()); // OK: we know T is a string
  return value;
}

const result = logAndReturn("hello"); // T inferred as "hello"
// logAndReturn(42); // Error: number doesn't extend string

By writing T extends string, you guarantee T is some kind of string—possibly a specific literal like "hello", but definitely not a number or object.

Constraining to Literal Unions

You can also constrain to a union of literals for extremely precise control:

function makeRequest<T extends "GET" | "POST">(method: T): T {
  return method;
}

const getReq = makeRequest("GET"); // T is "GET"
// const invalid = makeRequest("DELETE"); // Error: doesn't extend the union

This gives you type-safe APIs where only specific values are allowed, while still preserving the exact literal type through the generic.

Why This Matters

These constraints combine the flexibility of generics with the safety of specific types—you get reusability and precise autocomplete and error checking.

Key Takeaway: Use extends with primitive types or literal unions to constrain generics to exact categories of values, giving you both reusability and precision.