Interfaces describe object contracts; type aliases name any type, including unions and intersections. Use extends (or &) to compose, optional ? for fields that may be missing, and readonly for props you do not want assigned. Prefer a discriminated union over a pile of optional fields.
This TypeScript cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- Optional:
email?: stringmay beundefined. Combine with| nullif the API sends null. - readonly:
readonly id: number— assignment is a type error. - extends:
interface Admin extends User { role: "admin" }. - Intersection:
type A = B & Cmust satisfy both. - Union:
type Status = "draft" | "live"— use instead of magic booleans. - Index:
Record<string, number>or{ [slug: string]: Post }. - Merge: Two
interface Userin the same scope merge. Type aliases do not. - typeof / keyof:
keyof Useris"id" | "email".typeof configcaptures a value’s type.
Copy-paste examples
Compose and discriminate
A tag field (kind) lets switch narrow the rest of the object.
interface Timestamps {
createdAt: string;
updatedAt: string;
}
export interface Post extends Timestamps {
id: number;
title: string;
published?: boolean;
}
export type Nav =
| { kind: 'link'; href: string; label: string }
| { kind: 'group'; label: string; items: Nav[] };
export function hrefOf(item: Nav): string | null {
return item.kind === 'link' ? item.href : null;
}Common mistakes
- Optional everything (
user?: { email?: string }) so you never know what exists. - Extending interfaces in a
.d.tsyou do not own and breaking upgrades (unintentional merging). type X = {}which is surprisingly wide (almost everything exceptnull/undefinedin some configs).- Mixing
nullandundefinedwithout documenting which the API uses.
FAQ
- When must I use a type alias? Unions, tuples, mapped types, and
typeofresults cannot be expressed as an interface body alone.
- Can interfaces express unions? Not as the alias itself. An interface property can be a union. The whole type as A | B is a type alias.
- readonly array?
readonly string[]orReadonlyArray<string>.as conston literals is even narrower.
Related TypeScript cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.