TypeScript Types Cheat Sheet

A comprehensive reference guide for TypeScript's type system, from basic primitives to advanced conditional and mapped types.

Primitive Types

Type Description Example
string Text values let name: string = "Alice";
number Numeric values (integers and floats) let age: number = 30;
boolean True or false values let active: boolean = true;
null Intentional absence of value let data: null = null;
undefined Uninitialized value let value: undefined = undefined;
symbol Unique, immutable identifier let sym: symbol = Symbol("key");
bigint Arbitrary precision integers let big: bigint = 100n;
any Disable type checking (avoid when possible) let data: any = { x: 10 };
unknown Type-safe alternative to any (requires type checking) let value: unknown = 5;
never Values that never occur (unreachable code) function error(): never { throw new Error(); }
void Absence of a return value function log(): void { console.log("Hi"); }

Object Types

Pattern Description Example
interface Define object shape interface User { name: string; age: number; }
type alias Create custom type names type Point = { x: number; y: number; };
Optional properties Mark properties as optional interface User { email?: string; }
Readonly properties Immutable properties interface User { readonly id: number; }
Index signatures Dynamic property names interface StringMap { [key: string]: string; }
Extending interfaces Inherit properties from another interface interface Admin extends User { role: string; }
Object literal type Inline object type let user: { name: string; age: number };

Union & Intersection Types

Pattern Description Example
Union types | Value can be one of several types let id: string | number;
Intersection types & Combine multiple types type Person = Name & Age & Address;
Literal types Exact values as types let direction: "left" | "right" | "up" | "down";
Discriminated unions Union with common discriminant property type Shape = { kind: "circle"; radius: number } | { kind: "square"; size: number };
Type guards with unions Narrow union types if (typeof id === "string") { ... }

Arrays & Tuples

Pattern Description Example
Array type Array of specific type let numbers: number[] = [1, 2, 3];
Generic array Alternative array syntax let numbers: Array<number> = [1, 2, 3];
Readonly array Immutable array let nums: readonly number[] = [1, 2, 3];
Readonly generic Alternative readonly syntax let nums: ReadonlyArray<number> = [1, 2, 3];
Tuple Fixed-length array with specific types let tuple: [string, number] = ["Alice", 30];
Named tuple Tuple with labeled elements let point: [x: number, y: number] = [10, 20];
Optional tuple elements Optional elements in tuple let tuple: [string, number?] = ["Alice"];
Rest in tuples Variable length tuple suffix let args: [string, ...number[]] = ["msg", 1, 2, 3];

Functions

Pattern Description Example
Function type Type signature for function let fn: (x: number) => number;
Typed parameters Parameter types function add(a: number, b: number) { return a + b; }
Return type Explicit return type function getName(): string { return "Alice"; }
Optional parameters Parameters that may be omitted function greet(name?: string) { ... }
Default parameters Parameters with default values function greet(name = "Guest") { ... }
Rest parameters Variable number of arguments function sum(...nums: number[]): number { ... }
Function overloads Multiple function signatures function process(x: string): string;
function process(x: number): number;
this parameter Type the this context function fn(this: MyClass) { ... }
Void return Function returns nothing function log(msg: string): void { console.log(msg); }
Never return Function never returns function fail(msg: string): never { throw new Error(msg); }

Generics

Pattern Description Example
Generic function Function with type parameter function identity<T>(arg: T): T { return arg; }
Generic interface Interface with type parameter interface Box<T> { value: T; }
Generic class Class with type parameter class Container<T> { constructor(public value: T) {} }
Multiple type parameters More than one generic type function pair<T, U>(a: T, b: U): [T, U] { return [a, b]; }
Generic constraints Restrict generic type with extends function getLength<T extends { length: number }>(arg: T): number { return arg.length; }
Generic defaults Default type for generic interface Page<T = string> { data: T; }
Using type parameters Reference generic in constraints function getProperty<T, K extends keyof T>(obj: T, key: K) { return obj[key]; }
Generic type aliases Parameterized type alias type Result<T> = { success: true; value: T } | { success: false; error: string };

Utility Types

Utility Type Description Example
Partial<T> Make all properties optional type PartialUser = Partial<User>;
Required<T> Make all properties required type RequiredUser = Required<User>;
Readonly<T> Make all properties readonly type ReadonlyUser = Readonly<User>;
Record<K, T> Object type with keys K and values T type PageInfo = Record<string, { title: string }>;
Pick<T, K> Select specific properties from type type UserName = Pick<User, "name" | "email">;
Omit<T, K> Remove specific properties from type type UserWithoutId = Omit<User, "id">;
Exclude<T, U> Exclude types from union type T = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
Extract<T, U> Extract types from union type T = Extract<"a" | "b" | "c", "a" | "f">; // "a"
NonNullable<T> Remove null and undefined from type type T = NonNullable<string | null | undefined>; // string
ReturnType<T> Extract function return type type T = ReturnType<() => string>; // string
Parameters<T> Extract function parameter types as tuple type T = Parameters<(a: string, b: number) => void>; // [string, number]
InstanceType<T> Extract instance type of constructor type T = InstanceType<typeof MyClass>;
Awaited<T> Unwrap Promise type type T = Awaited<Promise<string>>; // string

Mapped Types

Pattern Description Example
Basic mapped type Transform properties of existing type type Flags<T> = { [K in keyof T]: boolean };
Optional modifier Make properties optional type Optional<T> = { [K in keyof T]?: T[K] };
Readonly modifier Make properties readonly type ReadOnly<T> = { readonly [K in keyof T]: T[K] };
Remove modifiers Remove optional/readonly with - type Mutable<T> = { -readonly [K in keyof T]: T[K] };
Key remapping Transform property keys with as type Getters<T> = { [K in keyof T as `get${Capitalize<K>}`]: () => T[K] };
Filter properties Conditionally include properties type StringProps<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K] };
Template literal keys Create new keys with template literals type Events<T> = { [K in keyof T as `on${Capitalize<K>}Change`]: (val: T[K]) => void };

Conditional Types

Pattern Description Example
Basic conditional Type selection based on condition type IsString<T> = T extends string ? true : false;
Distributive conditional Distributes over union types type ToArray<T> = T extends any ? T[] : never;
Non-distributive Prevent distribution with brackets type ToArray<T> = [T] extends [any] ? T[] : never;
infer keyword Extract type from conditional type ElementType<T> = T extends (infer U)[] ? U : never;
Infer return type Extract function return type type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
Infer parameters Extract function parameters type Params<T> = T extends (...args: infer P) => any ? P : never;
Nested conditionals Multiple conditional branches type TypeName<T> = T extends string ? "string" : T extends number ? "number" : "object";
Recursive conditionals Self-referencing conditional types type Flatten<T> = T extends Array<infer U> ? Flatten<U> : T;

Type Guards & Narrowing

Pattern Description Example
typeof guard Check primitive types if (typeof x === "string") { x.toUpperCase(); }
instanceof guard Check class instances if (x instanceof Date) { x.getTime(); }
in operator Check property existence if ("swim" in animal) { animal.swim(); }
User-defined type guard Custom type predicate with is function isString(x: any): x is string { return typeof x === "string"; }
Assertion signatures Assert type with asserts function assertString(x: any): asserts x is string { if (typeof x !== "string") throw new Error(); }
Truthiness narrowing Narrow with truthiness check if (value) { // value is truthy }
Equality narrowing Narrow with === comparison if (x === "admin") { // x is literal "admin" }
Discriminated unions Narrow tagged unions if (shape.kind === "circle") { shape.radius; }
Control flow analysis TypeScript tracks types through code flow let x: string | number;
x = "hello";
// x is now string

Template Literal Types

Pattern Description Example
Basic template literal String literal type with interpolation type World = "world";
type Greeting = `hello ${World}`; // "hello world"
Union in template Template with union creates all combinations type Color = "red" | "blue";
type Shade = "light" | "dark";
type ColorShade = `${Shade}-${Color}`; // "light-red" | "light-blue" | "dark-red" | "dark-blue"
Uppercase<T> Convert string to uppercase type Loud = Uppercase<"hello">; // "HELLO"
Lowercase<T> Convert string to lowercase type Quiet = Lowercase<"HELLO">; // "hello"
Capitalize<T> Capitalize first letter type Title = Capitalize<"hello">; // "Hello"
Uncapitalize<T> Uncapitalize first letter type Lower = Uncapitalize<"Hello">; // "hello"
Event names pattern Generate event handler names type EventNames<T> = { [K in keyof T as `on${Capitalize<string & K>}`]: () => void };
CSS property pattern Generate vendor-prefixed properties type Prefix<T extends string> = `webkit${Capitalize<T>}` | `moz${Capitalize<T>}` | T;

Declaration Files

Pattern Description Example
.d.ts files Type declaration files // myLib.d.ts
export function greet(name: string): void;
declare keyword Declare ambient types/values declare const API_URL: string;
Declare module Type external modules declare module "my-module" {
  export function hello(): string;
}
Declare global Add to global scope declare global {
  interface Window { myLib: MyLib; }
}
Ambient namespace Declare namespace types declare namespace MyLib {
  function init(): void;
}
Triple-slash directive Reference other declaration files /// <reference types="node" />
Module augmentation Extend existing module types declare module "express" {
  interface Request { user?: User; }
}
Wildcard module Type non-code imports declare module "*.css" {
  const content: { [key: string]: string };
  export default content;
}

Advanced Patterns

Pattern Description Example
keyof operator Get union of object keys type Keys = keyof { x: number; y: string }; // "x" | "y"
Indexed access Access property type type X = { a: number; b: string };
type A = X["a"]; // number
Type from value Extract type from value with typeof const config = { url: "...", port: 3000 };
type Config = typeof config;
Const assertions Literal types with as const const colors = ["red", "blue"] as const;
type Color = typeof colors[number]; // "red" | "blue"
Recursive types Self-referencing types type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };
Branded types Nominal typing with unique symbols type UserId = string & { readonly __brand: unique symbol };
Builder pattern Fluent API with conditional types type Builder<T, K extends keyof T = never> = {
  set<P extends keyof T>(key: P, value: T[P]): Builder<T, K | P>;
};
Variadic tuple types Generic spreads in tuples type Concat<T extends any[], U extends any[]> = [...T, ...U];

Type System Tips

Tip Description Example
Type vs Interface Interfaces can be extended, types can use unions // Both work, but interfaces are better for objects that will be extended
Avoid any Use unknown instead for better type safety let data: unknown; // Must check type before use
Strict mode Enable strict: true in tsconfig.json // Catches more errors at compile time
Type inference Let TypeScript infer when possible const x = 5; // TypeScript knows it's number
Use const assertions Get literal types instead of widened types const config = { mode: "prod" } as const;
Discriminated unions Use a common property for type narrowing // Add a "type" or "kind" field to union members
Avoid type assertions Use type guards instead of as when possible // Type guards are safer than assertions
Document complex types Use JSDoc comments for complex type utilities /** Extracts promise value type */
type Awaited<T> = ...