TypeScript cheat sheet
96 one-line examples for TypeScript. Open it while you code, or print it and keep it near the keyboard. Free, with no signup and no ads.
Basic Types
| Code | What it does |
|---|---|
let n: number = 5; | Declare a number variable. |
let s: string = "hi"; | Declare a text variable. |
let b: boolean = true; | Declare a true or false variable. |
let a: number[] = [1, 2]; | Declare an array of numbers. |
let t: [string, number]; | Declare a fixed tuple of two values. |
let u: unknown = 5; | Use unknown when the type is not known. |
let x: any = 5; | Use any to turn off type checks. |
let v: void = undefined; | Use void for functions with no return. |
let nl: null = null; | Declare a null value. |
let un: undefined = undefined; | Declare an undefined value. |
let big: bigint = 10n; | Declare a very large integer. |
let sym: symbol = Symbol(); | Declare a unique symbol value. |
Functions
| Code | What it does |
|---|---|
function add(a: number, b: number) { | Start a typed function with two numbers. |
function add(a: number, b: number): number { | Add a return type to the function. |
const add = (a: number, b: number) => a + b; | Write a typed arrow function. |
function greet(name: string = "Ann") {} | Set a default value for a parameter. |
function log(msg?: string) {} | Make a parameter optional with a question mark. |
function sum(...nums: number[]) {} | Collect many arguments into one array. |
type Fn = (a: number) => number; | Name a function type with type. |
let f: (a: number) => void; | Declare a variable that holds a function. |
function fail(): never { throw 1; } | Use never for a function that always throws. |
const g = function (a: number) {}; | Write a typed function expression. |
function id<T>(x: T): T { return x; } | Write a generic function that keeps the type. |
function cb(fn: () => void) {} | Pass a function as a parameter. |
Objects and Interfaces
| Code | What it does |
|---|---|
let user: { name: string }; | Declare an object with one property. |
interface User { name: string; } | Define an object shape with interface. |
interface User { age?: number; } | Make an object property optional. |
interface User { readonly id: number; } | Make a property read only. |
type Point = { x: number; y: number }; | Define an object shape with type. |
let p: Point = { x: 1, y: 2 }; | Create an object that matches the type. |
interface A extends B { } | Extend one interface from another. |
type C = A & B; | Combine two types into one. |
type U = A | B; | Allow one of two types. |
let o: Record<string, number> = {}; | Declare an object with string keys. |
interface User { [k: string]: number; } | Allow any string key with number values. |
let user = { name: "Ann" } as const; | Make object values read only literals. |
Arrays and Tuples
| Code | What it does |
|---|---|
let nums: number[] = [1, 2, 3]; | Declare an array of numbers. |
let names: Array<string> = []; | Declare an array with generic syntax. |
let pair: [string, number] = ["a", 1]; | Declare a tuple with two fixed types. |
let ro: readonly number[] = [1]; | Declare an array you cannot change. |
nums.push(4); | Add one item to the end. |
nums.map((n) => n * 2); | Make a new array from each item. |
nums.filter((n) => n > 1); | Keep only items that pass a test. |
nums.reduce((a, n) => a + n, 0); | Combine all items into one value. |
nums.forEach((n) => console.log(n)); | Run a function for each item. |
let first = nums[0]; | Read the first item by index. |
let len = nums.length; | Get the number of items. |
let found = nums.find((n) => n > 2); | Get the first item that matches. |
Union and Narrowing
| Code | What it does |
|---|---|
let id: string | number; | Allow a string or a number. |
type Status = "on" | "off"; | Allow only two text values. |
if (typeof id === "string") {} | Check the type before you use it. |
if ("name" in obj) {} | Check that a property exists. |
if (x instanceof Date) {} | Check the class of an object. |
if (x === null) {} | Check for a null value. |
if (x) { } | Check that a value is truthy. |
let s = x as string; | Tell the compiler the type yourself. |
let s = x!; | Remove null and undefined from a type. |
function f(x: string | number) {} | Accept two possible types. |
type T = Exclude<U, null>; | Remove one type from a union. |
switch (x) { case "a": break; } | Narrow a union with a switch. |
Classes
| Code | What it does |
|---|---|
class User { name: string = ""; } | Declare a class with one field. |
class User { constructor(public name: string) {} } | Create and assign a field in one step. |
class User { private age = 0; } | Hide a field from outside code. |
class User { readonly id = 1; } | Make a field read only. |
class Admin extends User {} | Create a subclass from a parent class. |
super(name); | Call the parent constructor. |
class User { greet(): string { return "hi"; } } | Add a method with a return type. |
class User { static count = 0; } | Add a field that belongs to the class. |
abstract class Shape { } | Declare a base class you cannot create. |
class User implements Person {} | Make a class follow an interface. |
class User { get name() { return "a"; } } | Add a getter for a property. |
class User { protected id = 1; } | Allow subclasses to use the field. |
Generics
| Code | What it does |
|---|---|
function id<T>(x: T): T { return x; } | Keep the input type in the output. |
let a = id<number>(5); | Set the type argument yourself. |
interface Box<T> { value: T; } | Declare an interface with a type parameter. |
let b: Box<string> = { value: "a" }; | Use the interface with a set type. |
type Pair<T> = [T, T]; | Declare a type alias with a parameter. |
function f<T extends object>(x: T) {} | Limit the type parameter to objects. |
function f<T = string>() {} | Set a default type argument. |
function f<K extends keyof T>() {} | Limit a key to the keys of T. |
class Store<T> { items: T[] = []; } | Declare a class with a type parameter. |
function first<T>(a: T[]): T { return a[0]; } | Return one item from a typed array. |
let m = new Map<string, number>(); | Use a built in type with two arguments. |
function f<T, U>(a: T, b: U) {} | Use two type parameters. |
Utility Types
| Code | What it does |
|---|---|
type P = Partial<User>; | Make all properties optional. |
type R = Required<User>; | Make all properties required. |
type RO = Readonly<User>; | Make all properties read only. |
type PickU = Pick<User, "id">; | Keep only the listed properties. |
type OmitU = Omit<User, "id">; | Remove the listed properties. |
type Rec = Record<string, number>; | Map string keys to number values. |
type NN = NonNullable<string | null>; | Remove null and undefined from a type. |
type Ret = ReturnType<typeof fn>; | Get the return type of a function. |
type Par = Parameters<typeof fn>; | Get the parameter types as a tuple. |
type Ex = Exclude<"a" | "b", "a">; | Remove one member from a union. |
type Ext = Extract<"a" | "b", "a">; | Keep only the matching union members. |
type Aw = Awaited<Promise<number>>; | Get the value type inside a promise. |