Understanding TypeScript Generics

1989

Understanding TypeScript Generics

Generics are one of TypeScript's most powerful features. They allow you to write reusable, type-safe code without sacrificing flexibility.

What Are Generics?

Generics let you parameterize types, much like functions parameterize values:

// A function that works with ANY type
function identity<T>(arg: T): T {
  return arg;
}

const num = identity(42);        // type: number
const str = identity("hello");   // type: string

Generic Constraints

You can constrain what types are accepted:

interface HasLength {
  length: number;
}

function logLength<T extends HasLength>(arg: T): T {
  console.log(arg.length);
  return arg;
}

logLength("hello");     // ✅ string has length
logLength([1, 2, 3]);   // ✅ array has length
// logLength(42);        // ❌ number has no length

Generic Utility Types

TypeScript provides built-in generic types:

type Partial<T> = { [K in keyof T]?: T[K] };
type Readonly<T> = { readonly [K in keyof T]: T[K] };
type Pick<T, K extends keyof T> = { [P in K]: T[P] };

Real-World Example

async function fetchJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  return res.json() as Promise<T>;
}

interface User {
  id: number;
  name: string;
}

const user = await fetchJson<User>('/api/user');
// user is typed as User

Generics make your code both flexible and type-safe — the best of both worlds.

Comments

Loading comments...

Leave a comment

Your name and email are saved locally in your browser so you don't have to re-enter them.