← TypeScript

Advanced · 6 of 12 · 15 min read

Deriving types from types

Single source of truth in the type system — typeof, as const, indexed access and schema inference, so a shape is declared once and everything else follows.

  • Utility types

Two declarations of the same shape will drift. The question is never whether to write it twice, but which one is the source — and TypeScript gives you the tools to generate the rest either way.

typeof, in type position

const defaults = {
  host: "localhost",
  port: 3000,
  retries: 3,
};

type Config = typeof defaults;
// { host: string; port: number; retries: number }

function connect(config: Config) { return `${config.host}:${config.port}`; }
console.log(connect({ ...defaults, port: 8080 }));

The type is now a consequence of the object. Add a field to defaults and Config grows; there is no second place to update and no way for the two to disagree.

typeof also reaches functions and classes, which is where ReturnType and InstanceType come in:

function createUser(name: string, age: number) {
  return { id: crypto.randomUUID(), name, age, createdAt: new Date() };
}

type User = ReturnType<typeof createUser>;
type Args = Parameters<typeof createUser>;

class Repo { find(id: string) { return id; } }
type RepoInstance = InstanceType<typeof Repo>;  // Repo

const args: Args = ["Ana", 30];
const user: User = createUser(...args);
declare const repo: RepoInstance;
console.log(user.name, repo.find("1"));

Note typeof Repo versus Repo: the first is the type of the class value — the constructor, with the statics on it — and the second is the instance type. A function that takes a class as an argument needs the former.

as const and the two directions

Without as const, a literal widens and the derived type loses the information you wanted:

const routes = { home: "/", users: "/users" };
type Route = typeof routes[keyof typeof routes];  // string — useless

const frozen = { home: "/", users: "/users" } as const;
type Better = typeof frozen[keyof typeof frozen];  // "/" | "/users"

const route: Better = "/users";
console.log(route);

typeof x[keyof typeof x] is the idiom for “the union of this object’s values”, and it only says anything when the values did not widen. The same for an array:

const levels = ["debug", "info", "error"] as const;

type Level = typeof levels[number];  // "debug" | "info" | "error"

function log(level: Level, message: string) { console.log(level, message); }
log("info", "ready");
levels.forEach((level) => log(level, "ok"));  // and the array is iterable at runtime

That pattern — a const array plus [number] — is the replacement for an enum in most code: one declaration gives you the runtime list to iterate and the literal union to check against.

The opposite direction starts from the type:

type Level = "debug" | "info" | "error";

const colours: Record<Level, string> = {
  debug: "grey",
  info: "blue",
  error: "red",
};
// Add a level to the union and this object is a compile error until handled.

console.log(Object.keys(colours));
Source of truth Derive with Use when
A runtime object typeof, typeof x[keyof typeof x] the values are needed at runtime
A runtime array as const + [number] you need to iterate the options
A function ReturnType, Parameters the shape is whatever the function produces
A class InstanceType, typeof C passing classes around
A type Record<K, V> the union is the primary declaration
A validator z.infer and friends the data comes from outside the program

Indexed access

Reaching into a type is the cheapest form of deriving, and it is underused:

interface AppState {
  user: { id: number; name: string; roles: string[] };
  settings: { theme: "light" | "dark" };
}

type User = AppState["user"];
type Role = AppState["user"]["roles"][number];
type Theme = AppState["settings"]["theme"];      // "light" | "dark"
type Any = AppState[keyof AppState];             // the union of both slices

const theme: Theme = "dark";
const role: Role = "admin";
console.log(theme, role);

[number] on an array type gets the element; chaining works to any depth; [keyof T] gets the union of all values. No new declaration, and nothing to keep in sync.

It works on tuples and function parameters too:

type Pair = [name: string, age: number];
type Name = Pair[0];       // string
type Either = Pair[number]; // string | number

function send(message: { to: string; body: string }) { return message.to; }
type Message = Parameters<typeof send>[0];

const message: Message = { to: "a@b.c", body: "hi" };
console.log(send(message));

Parameters<typeof fn>[0] is how you name an argument type that was declared inline — common when the function is someone else’s.

Schema-first

For data that crosses a boundary, the runtime validator should be the source and the type should be derived from it. This is the shape every schema library has:

// Sketch of what z.infer does, without the dependency:
interface Schema<T> { parse(input: unknown): T }
type Infer<S> = S extends Schema<infer T> ? T : never;

declare const userSchema: Schema<{ id: number; name: string }>;
type User = Infer<typeof userSchema>;

function handle(input: unknown) {
  const user: User = userSchema.parse(input);
  return user.name;
}
console.log(typeof handle);

The point is the direction. A hand-written interface User plus a hand-written validator are two declarations of one shape, and the validator is the one that will fall behind — silently, because nothing checks a validator against a type. Derive and there is only one.

Deriving the variants of a shape

Most “almost the same type” problems are a derivation:

interface User {
  id: number;
  name: string;
  email: string;
  passwordHash: string;
  createdAt: Date;
}

type PublicUser = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id" | "createdAt" | "passwordHash">;
type UserPatch = Pick<User, "id"> & Partial<Omit<User, "id">>;
type UserKey = keyof User;

const draft: NewUser = { name: "Ana", email: "a@b.c" };
const patch: UserPatch = { id: 1, email: "new@b.c" };
console.log(draft.name, patch.email);

Five related types, one declaration. The alternative — interface PublicUser { id: number; name: string } written out — is correct today and wrong after the next rename.

Pick over Omit for anything exposed, for the reason given in the utility-types lecture: the whitelist fails safe when the source type grows.

Deriving across a boundary

The same discipline applies between layers, where the temptation to re-declare is strongest:

interface DbUser { id: number; name: string; password_hash: string }

type ApiUser = {
  [K in keyof Pick<DbUser, "id" | "name"> as K extends "id" ? "userId" : K]: DbUser[K];
};
// { userId: number; name: string }

const api: ApiUser = { userId: 1, name: "Ana" };
console.log(api.userId);

Whether this is better than writing interface ApiUser by hand is a real judgement call, and the test is how often the two shapes change together. If the API contract is deliberately independent of the database — which is usually the point of having one — then two declarations are honest, and a mapping function is the place the drift gets caught.

Common mistakes

typeof without as const

Mistake. Deriving a union of values from a plain object literal. Why it fails. The literals widened to string when the object was declared, so the derived type says nothing. What to do instead. as const on the value, or satisfies when you also want it checked.

Re-declaring what the function already says

Mistake. An interface ApiResponse alongside the function that builds the response. Why it fails. Two declarations, one of which is updated. What to do instead. ReturnType<typeof buildResponse>, or go the other way and annotate the function with the interface — but pick one.

Deriving a type from a value that is not the source of truth

Mistake. type Config = typeof devDefaults where the real shape lives in the schema. Why it fails. The defaults are one instance of the shape, not its definition; an optional field absent from the defaults disappears from the type. What to do instead. Derive from the schema or declare the type, and make the defaults satisfies Config.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

An intersection of mapped types shows the shape; a single mapped type over it shows the result.

Why does the editor show A & B instead of the combined object?

Code sample
type A = { id: number };
type B = { name: string };

type Combined = A & B;

How would you write a DeepPartial<T>?

Extract and Exclude filter a union, and they work on object members too.

What does Extract<State, { status: "ok" }> give you?

Code sample
type State =
  | { status: "ok"; data: string }
  | { status: "fail"; error: string };
Practise Utility types →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.