by DannyUpdated 9 sections

Examples assume TypeScript 5 with strict turned on.

Download the PDF

Basic types


_10
let id: number = 1;
_10
let name: string = 'Ann';
_10
let tags: string[] = [];
_10
let pair: [string, number] = ['a', 1];
_10
let anything: unknown; // safer than any
_10
function log(msg: string): void {}

Types and interfaces


_10
type Id = string | number; // union
_10
type Point = { x: number; y: number };
_10
interface User {
_10
id: Id;
_10
name: string;
_10
email?: string; // optional
_10
readonly createdAt: Date;
_10
}
_10
interface Admin extends User { role: 'admin' }

Literal types


_10
type Status = 'idle' | 'loading' | 'done';
_10
const sizes = ['sm', 'md', 'lg'] as const;
_10
type Size = (typeof sizes)[number]; // 'sm' | ...

Generics


_10
function first<T>(list: T[]): T | undefined {
_10
return list[0];
_10
}
_10
type ApiResult<T> = { data: T; error?: string };
_10
function byId<T extends { id: string }>(xs: T[]) {}

Utility types


_10
Partial<User> // every key optional
_10
Required<User> // every key required
_10
Pick<User, 'id'> // only these keys
_10
Omit<User, 'email'> // all but these keys
_10
Record<string, User> // object map
_10
ReturnType<typeof fn> // what fn returns
_10
Awaited<Promise<T>> // T
_10
NonNullable<T | null> // T

Narrowing


_10
if (typeof id === 'string') id.toUpperCase();
_10
if ('role' in user) user.role;
_10
if (err instanceof Error) err.message;
_10
_10
function isUser(x: unknown): x is User {
_10
return typeof x === 'object' && x !== null
_10
&& 'id' in x;
_10
}

Exhaustive checks


_11
function label(s: Status) {
_11
switch (s) {
_11
case 'idle': return 'Waiting';
_11
case 'loading': return 'Loading';
_11
case 'done': return 'Done';
_11
default: {
_11
const never: never = s; // errors if missed
_11
return never;
_11
}
_11
}
_11
}

Handy operators


_10
const config = { port: 3000 } satisfies Config;
_10
const el = document.querySelector('a')!; // not null
_10
type Keys = keyof User; // 'id' | 'name' ...
_10
type Name = User['name']; // string

tsconfig essentials


_10
{
_10
"compilerOptions": {
_10
"strict": true,
_10
"target": "ES2022",
_10
"module": "NodeNext",
_10
"noUncheckedIndexedAccess": true,
_10
"skipLibCheck": true
_10
}
_10
}