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.
Gotchas worth knowing
- •Let TypeScript infer types you do not need to spell out. const n = 5 is already number; annotate function parameters and public APIs, not every local.
- •Avoid any. It silently turns off type checking. Reach for unknown when a value's type is genuinely unknown, then narrow it.
- •interface and type overlap a lot. A common rule: interface for object shapes you might extend, type for unions and aliases.
- •Types vanish at runtime. TypeScript compiles to plain JavaScript, so you cannot check a type with an if at runtime; narrow with typeof, in, or instanceof instead.