Advanced TypeScript Types

Type-level programming — keyof and indexed access, typeof, mapped types, conditional types and infer, template literal types, utility types (Partial, Pick, Omit, ReturnType…), variance, branded types, and satisfies.

Advanced 2 min readLesson 12 of 12

TypeScript's type system is a small programming language of its own. Types can be computed from other types, which lets you keep one source of truth and derive everything else. This lesson covers the building blocks behind libraries like Prisma, tRPC and zod.

keyof, typeof and indexed access

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

type UserKey = keyof User;                // "id" | "name" | "age"
type NameType = User["name"];             // string
type IdOrAge = User["id" | "age"];        // string | number

const config = { port: 3000, host: "localhost", debug: false };
type Config = typeof config;              // { port: number; host: string; debug: boolean }

const roles = ["admin", "editor", "viewer"] as const;
type Role = (typeof roles)[number];       // "admin" | "editor" | "viewer"

// Type-safe property access
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
get(user, "age");      // number
get(user, "email");    // ✗ "email" is not a key of User

Mapped types

Transform every property of a type:

TypeScript
type Optional<T> = { [K in keyof T]?: T[K] };              // like Partial<T>
type ReadonlyDeep<T> = { readonly [K in keyof T]: T[K] extends object ? ReadonlyDeep<T[K]> : T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };

// Modifiers: add/remove readonly and ?
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Concrete<T> = { [K in keyof T]-?: T[K] };              // like Required<T>

// Key remapping with 'as' (4.1+)
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
type UserGetters = Getters<User>;   // { getId: () => string; getName: () => string; getAge: () => number }

// Filter keys
type OnlyStrings<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K] };
type UserStrings = OnlyStrings<User>;   // { id: string; name: string }

Conditional types

Type-level if: T extends U ? X : Y.

TypeScript
type IsString<T> = T extends string ? true : false;
type A = IsString<"hi">;    // true
type B = IsString<42>;      // false

// Distributive over unions when T is a naked type parameter
type NonNullable2<T> = T extends null | undefined ? never : T;
type C = NonNullable2<string | null | undefined>;   // string

type ToArray<T> = T extends unknown ? T[] : never;
type D = ToArray<string | number>;                  // string[] | number[]
type ToArrayNonDist<T> = [T] extends [unknown] ? T[] : never;
type E = ToArrayNonDist<string | number>;           // (string | number)[]

infer: extracting types

TypeScript
type ElementType<T> = T extends (infer U)[] ? U : never;
type F = ElementType<number[]>;                     // number

type Awaited2<T> = T extends Promise<infer U> ? Awaited2<U> : T;   // recursive unwrap
type G = Awaited2<Promise<Promise<string>>>;         // string

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

async function fetchUser(id: string) { return { id, name: "Ada" }; }
type FetchedUser = Awaited<ReturnType<typeof fetchUser>>;   // { id: string; name: string }

Template literal types

TypeScript
type HttpMethod = "GET" | "POST";
type Route = "/users" | "/orders";
type Endpoint = `${HttpMethod} ${Route}`;     // "GET /users" | "GET /orders" | "POST /users" | "POST /orders"

type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickHandler = EventName<"click">;       // "onClick"

// Parse a route's params at the type level
type Params<S extends string> =
  S extends `${string}:${infer P}/${infer Rest}` ? P | Params<`/${Rest}`>
  : S extends `${string}:${infer P}` ? P
  : never;
type RouteParams = Params<"/users/:userId/posts/:postId">;   // "userId" | "postId"

Built-in string helpers: Uppercase, Lowercase, Capitalize, Uncapitalize.

The built-in utility types

UtilityResult
Partial<T> / Required<T>All properties optional / required
Readonly<T>All properties readonly
Pick<T, K> / Omit<T, K>Keep / remove some keys
Record<K, V>Object with keys K and values V
Exclude<U, X> / Extract<U, X>Remove / keep union members assignable to X
NonNullable<T>Remove null and undefined
ReturnType<F> / Parameters<F>A function's return / parameter tuple types
Awaited<T>Unwrap promises recursively
InstanceType<C> / ConstructorParameters<C>For class constructors
NoInfer<T>Block inference from a position (5.4+)
TypeScript
type CreateUserInput = Omit<User, "id">;                   // derive DTOs from the model
type UserUpdate = Partial<Pick<User, "name" | "age">>;
type RoleCounts = Record<Role, number>;                    // must have every role key

satisfies

Check that a value matches a type without widening its inferred type:

TypeScript
type Theme = Record<string, string | [number, number, number]>;

const palette = {
  red: [255, 0, 0],
  green: "#00ff00",
} satisfies Theme;

palette.red.map((c) => c / 255);     // ✓ still known to be a tuple
palette.green.toUpperCase();         // ✓ still known to be a string
// With 'const palette: Theme = ...' both would be string | [number, number, number]

Branded (nominal) types

Structural typing means UserId and OrderId (both strings) are interchangeable — a source of bugs. Brands add a phantom property:

TypeScript
type Brand<T, B extends string> = T & { readonly __brand: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;

const UserId = (s: string) => s as UserId;
function getOrder(id: OrderId) {}
getOrder(UserId("u_1"));     // ✗ compile error

Variance in brief

  • Object property types and return types are covariant: () => Dog is assignable to () => Animal.
  • Function parameters are checked contravariantly under strictFunctionTypes: a (a: Animal) => void can be used where (d: Dog) => void is expected, not the reverse. (Method-shorthand parameters are bivariant for historical reasons.)
  • You can annotate generic variance explicitly: interface Producer<out T>, interface Consumer<in T>.

A practical example: a typed event emitter

TypeScript
type Events = {
  login: { userId: string };
  logout: undefined;
  purchase: { orderId: string; amount: number };
};

class TypedEmitter<E extends Record<string, unknown>> {
  private handlers: { [K in keyof E]?: Array<(payload: E[K]) => void> } = {};

  on<K extends keyof E>(event: K, fn: (payload: E[K]) => void) {
    (this.handlers[event] ??= []).push(fn);
    return () => { this.handlers[event] = this.handlers[event]!.filter((f) => f !== fn); };
  }
  emit<K extends keyof E>(event: K, payload: E[K]) {
    this.handlers[event]?.forEach((fn) => fn(payload));
  }
}

const bus = new TypedEmitter<Events>();
bus.on("purchase", ({ orderId, amount }) => console.log(orderId, amount));   // payload fully typed
bus.emit("purchase", { orderId: "o1", amount: 42 });
bus.emit("login", { user: "x" });      // ✗ 'user' does not exist; 'userId' is missing
Key takeaways
  • keyof, typeof and indexed access derive types from existing values and types.
  • Mapped types transform every property; as-clauses rename or filter keys.
  • Conditional types branch on assignability; infer extracts parts of types; they distribute over unions.
  • Template literal types compute string types.
  • Utility types (Partial, Pick, Omit, Record, ReturnType, Awaited) cover most needs.
  • satisfies checks without widening; brands add nominal safety.