Updated Nov 29, 2026

07 - Generics and Utility Types

📋 Jump to Takeaways

🎁 Go generics let you write func Map[T, U any](...). TypeScript generics let you do that too — but also compute entirely new types at compile time. Partial<T>, Pick<T, K>, ReturnType<F> — these aren't library functions, they're the type system doing real work.

Generics let you write code that works with any type without losing type safety. If you've used generics in Go or Java, same concept. TypeScript's version is more powerful because it can compute new types from existing ones.

Generic Functions

A function that works with any type T.

function identity<T>(value: T): T {
  return value;
}

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

TypeScript infers T from the argument. You rarely need to specify it explicitly.

Compare to Go:

// Go
func Identity[T any](value T) T { return value }

Same idea. TypeScript just gives you more to work with after declaring T.

Generic Constraints

Use extends to restrict what T can be.

function getLength<T extends { length: number }>(item: T): number {
  return item.length;
}

console.log(getLength("hello"));    // 5
console.log(getLength([1, 2, 3]));  // 3
// getLength(42); // Error: number doesn't have 'length'

In Go, you'd write [T interface{ Len() int }]. Same concept, different syntax.

interface HasId {
  id: string;
}

function findById<T extends HasId>(items: T[], id: string): T | undefined {
  return items.find((item) => item.id === id);
}

const users = [
  { id: "1", name: "Alice", role: "admin" },
  { id: "2", name: "Bob", role: "user" },
];

const found = findById(users, "1");
// type: { id: string; name: string; role: string } | undefined
console.log(found?.name); // "Alice"

The return type preserves the full type of the input, not just HasId. That's the whole point.

keyof and Indexed Access Types

keyof gives you a union of an object type's keys.

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

type UserKey = keyof User; // "id" | "name" | "email"

Combine it with generics for type-safe property access:

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user: User = { id: 1, name: "Alice", email: "[email protected]" };

const name = getProperty(user, "name");  // type: string
const id = getProperty(user, "id");      // type: number
// getProperty(user, "age"); // Error: "age" is not in "id" | "name" | "email"

T[K] is an indexed access type. It looks up the type of property K on type T.

Mapped Types

Mapped types iterate over keys and transform each property. This is how the built-in utility types work.

// Make every property optional
type MyPartial<T> = {
  [K in keyof T]?: T[K];
};

// Make every property readonly
type MyReadonly<T> = {
  readonly [K in keyof T]: T[K];
};

// Make every property a string
type Stringify<T> = {
  [K in keyof T]: string;
};

type UserForm = MyPartial<User>;
// { id?: number; name?: string; email?: string }

type ReadonlyUser = MyReadonly<User>;
// { readonly id: number; readonly name: string; readonly email: string }

type UserStrings = Stringify<User>;
// { id: string; name: string; email: string }

Built-in Utility Types

TypeScript ships with utility types that cover the common cases. Don't reinvent these.

Pick and Omit

type UserPreview = Pick<User, "id" | "name">;
// { id: number; name: string }

type UserWithoutEmail = Omit<User, "email">;
// { id: number; name: string }

Partial and Required

interface Config {
  host: string;
  port: number;
  debug?: boolean;
}

type OptionalConfig = Partial<Config>;
// { host?: string; port?: number; debug?: boolean }

type StrictConfig = Required<Config>;
// { host: string; port: number; debug: boolean }

function createConfig(overrides: Partial<Config>): Config {
  return { host: "localhost", port: 3000, ...overrides };
}

console.log(createConfig({ port: 8080 }));
// { host: "localhost", port: 8080 }

Readonly and Record

type FrozenUser = Readonly<User>;
const user: FrozenUser = { id: 1, name: "Alice", email: "[email protected]" };
// user.name = "Bob"; // Error: Cannot assign to 'name'

type StatusMap = Record<string, number>;
const codes: StatusMap = { ok: 200, notFound: 404 };

ReturnType and Parameters

function createUser(name: string, email: string) {
  return { id: Math.random(), name, email, createdAt: new Date() };
}

type NewUser = ReturnType<typeof createUser>;
// { id: number; name: string; email: string; createdAt: Date }

type CreateUserArgs = Parameters<typeof createUser>;
// [name: string, email: string]

Use these to derive types from existing functions instead of duplicating definitions.

Conditional Types

Types can have if/else logic.

type IsString<T> = T extends string ? true : false;

type A = IsString<string>;  // true
type B = IsString<number>;  // false

More practical:

type ApiResponse<T> = T extends undefined
  ? { success: boolean }
  : { success: boolean; data: T };

type EmptyResponse = ApiResponse<undefined>;
// { success: boolean }

type UserResponse = ApiResponse<User>;
// { success: boolean; data: User }

The infer Keyword

infer extracts types from inside other types. Only works inside conditional types.

// Extract the resolved type from a Promise
type Unwrap<T> = T extends Promise<infer U> ? U : T;

type X = Unwrap<Promise<string>>;  // string
type Y = Unwrap<Promise<number>>;  // number
type Z = Unwrap<boolean>;          // boolean (not a Promise, returned as-is)

Extract function return types (this is how ReturnType works internally):

type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

type D = MyReturnType<() => string>;           // string
type E = MyReturnType<(x: number) => boolean>; // boolean

Extract array element types:

type ElementOf<T> = T extends (infer E)[] ? E : never;

type F = ElementOf<string[]>;  // string
type G = ElementOf<number[]>;  // number

Template Literal Types

TypeScript can compute string types.

type Method = "get" | "post" | "put" | "delete";
type Route = "/users" | "/posts";

type Endpoint = `${Uppercase<Method>} ${Route}`;
// "GET /users" | "GET /posts" | "POST /users" | "POST /posts" | ...

type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"
type LoadEvent = EventName<"load">;   // "onLoad"

Real World Example: Typed API Client

Putting it all together. A typed API client where the return type depends on the endpoint.

interface ApiEndpoints {
  "/users": User[];
  "/users/:id": User;
  "/posts": { id: number; title: string }[];
  "/health": { status: "ok" };
}

async function apiGet<T extends keyof ApiEndpoints>(
  endpoint: T
): Promise<ApiEndpoints[T]> {
  const response = await fetch(`https://api.example.com${endpoint}`);
  return response.json() as Promise<ApiEndpoints[T]>;
}

const users = await apiGet("/users");   // type: User[]
const health = await apiGet("/health"); // type: { status: "ok" }
// await apiGet("/unknown"); // Error: "/unknown" is not assignable

The endpoint string determines the return type. No runtime overhead. Pure compile-time safety.

Key Takeaways

  • Generic constraints (extends) restrict type parameters. Use them to require specific shapes.
  • keyof and indexed access types (T[K]) let you write functions that are type-safe over any object's properties.
  • Mapped types transform every property of a type. The built-in utilities (Pick, Omit, Partial, Required, Readonly, Record) cover most cases.
  • Conditional types add if/else logic to the type system. infer extracts types from inside other types.
  • Template literal types compute string types. Combine them with mapped types for powerful patterns.
  • Use ReturnType and Parameters to derive types from functions instead of duplicating definitions.

🎁 Go has goroutines and channels. Node.js has one thread and an event loop. How do you run a hundred database calls "at the same time" without spawning a single thread — and what actually happens when two of them resolve at once?

📝 Ready to test your knowledge?

Answer the quiz below to mark this lesson complete.

Spot something off? Report an issue