Cheat sheet · Languages
TypeScript cheat sheet
Types, interfaces, generics and the built-in helper types, with the checks that keep code safe.
- Sections
- 6
- Items
- 34
- Area
- Languages
- Download
- PNG, PDF
Cheat sheet
TypeScript
Types, interfaces, generics and the built-in helper types, with the checks that keep code safe.
Basic types
let n: number = 1- number, string, boolean
let list: string[]- An array of strings
let pair: [string, number]- A tuple: fixed length and order
let x: unknown- Any value; you must check it before use
let y: any- Turns type checking off (avoid)
function f(): void { }- Returns nothing
never- A value that cannot happen
Shapes
interface User { id: number; name: string }- Describe an object
type Id = string | number- A union: one of several types
type Both = A & B- An intersection: has everything from both
name?: string- An optional property
readonly id: number- A property that cannot be changed
type Mode = "light" | "dark"- Only these exact values
Functions
(a: number, b: number): number => a + b- Typed parameters and result
type Fn = (x: string) => void- A function type
function f<T>(x: T): T { return x }- A generic: works for any type T
f<string>("a")- Choose T yourself
Helper types
Partial<T>- All properties optional
Required<T>- All properties required
Pick<T, "a" | "b">- Keep only a and b
Omit<T, "a">- Everything except a
Record<string, number>- An object with string keys and number values
Readonly<T>- No property can change
ReturnType<typeof fn>- The type fn returns
Narrowing
typeof x === "string"- Check a basic type
x instanceof Date- Check a class
"name" in obj- Check a property exists
if (x) { }- Remove null and undefined
x as string- Tell TypeScript you know better (use rarely)
x!- Say x is not null (use rarely)
Useful extras
const colors = ["red", "blue"] as const- Exact values, read only
value satisfies Type- Check a value against a type without widening it
enum Role { Admin, User }- A named set of values
import type { User } from "./types"- Import only a type
Remember
- Turn on "strict": true in tsconfig.json. It catches the most bugs.
- Prefer unknown over any, and narrow it with a check.
- Types exist only while you write code. They are removed when the program runs.
Learn it properly
A cheat sheet helps you remember. These lessons explain the ideas step by step, with examples.