TypeScript Cheat Sheet
Quick reference from FreeCodingCourses.com
Basic types
let n: number = 5- explicit annotation (often inferred, so optional).
let s: string let ok: boolean- the primitives.
let xs: number[]- array of numbers. Also Array<number>.
let pair: [string, number]- tuple: fixed length and types.
let x: any let y: unknown- any turns off checks; unknown forces you to narrow first.
let id: string | number- union: one type or the other.
Objects and interfaces
interface User { name: string age?: number }- shape of an object. age? is optional.
type User = { name: string; age: number }- type alias, does the same job here.
interface User { readonly id: string }- readonly blocks reassignment.
const u: User = { name: 'Ada' }- TypeScript checks it matches the shape.
type ID = string | number- type is best for unions and primitives; interface for object shapes.
Functions
function add(a: number, b: number): number- typed params and return.
const add = (a: number, b: number): number => a + b- same as an arrow function.
function log(msg: string): void- void means it returns nothing useful.
function greet(name = 'friend'): string- default gives the param its type.
function f(x?: number)- optional param, type is number | undefined.
Narrowing a union
if (typeof id === 'string') { id.toUpperCase() }- inside the block, id is a string.
if ('email' in user) { ... }- narrow by checking a property exists.
if (x !== null) { ... }- rule out null / undefined before use.
value ?? 'default'- use the right side only when value is null or undefined.
Generics
function first<T>(xs: T[]): T { return xs[0] }- T is whatever type you pass in.
first([1, 2, 3]) // T is number- the type is inferred from the argument.
interface Box<T> { value: T }- generic type: Box<string>, Box<User>.
function keyOf<T, K extends keyof T>(o: T, k: K)- constrain a type param with extends.
Utility types
Partial<User>- all properties optional.
Required<User>- all properties required.
Pick<User, 'name'>- keep only the named keys.
Omit<User, 'password'>- everything except the named keys.
Record<string, number>- object with string keys and number values.
Unlock the full TypeScript cheat sheet
You're seeing 2 of 6 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.
No spam, unsubscribe anytime. See our privacy policy.