AI Generate TypeScript docs instantly

TypeScript Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Your first steps with TypeScript basics

Hello World

console.log("Hello, World!");

Type Annotation

let name: string = "John";
let age: number = 25;

Type Inference

let name = "John";  // inferred as string
let count = 0;      // inferred as number

Compile

tsc file.ts        // Compile to JS
tsc --watch        // Watch mode

Strict Mode

// tsconfig.json
{ "compilerOptions": { "strict": true } }

Basic Types

8 snippets

Type annotations for variables

String

let name: string = "John";

Number

let age: number = 25;

Boolean

let isActive: boolean = true;

Array

let nums: number[] = [1, 2, 3];
let strs: Array<string> = ["a", "b"];

Tuple

let tuple: [string, number] = ["age", 25];

Any

let data: any = "anything";

Unknown

let value: unknown = getValue();

Void/Never

function log(msg: string): void {}
function fail(): never { throw new Error(); }

Operators

6 snippets

Type operators and assertions

Type Assertion

const len = (value as string).length;
const len = (<string>value).length;

Non-null Assertion

const el = document.getElementById("id")!;
el.textContent = "Hello";

Optional Chaining

obj?.property
obj?.method?.()
arr?.[index]

Nullish Coalescing

const name = value ?? "default";
let x = 0;
x ??= 10;  // x stays 0

Satisfies

const config = {
    port: 3000,
} satisfies Config;

Keyof/Typeof

type Keys = keyof User;  // "name" | "age"
type UserType = typeof user;

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Loops

7 snippets

Repeat code with type safety

For

for (let i = 0; i < 5; i++) {
    console.log(i);
}

For...of (Arrays)

for (const item of array) {
    console.log(item);
}

For...in (Objects)

for (const key in object) {
    console.log(key, object[key]);
}

ForEach (Typed)

const nums: number[] = [1, 2, 3];
nums.forEach((n: number) => console.log(n));

While

while (count < 10) {
    count++;
}

Map with Types

const doubled: number[] = nums.map(
    (n: number): number => n * 2
);

Reduce with Types

const sum: number = nums.reduce(
    (acc: number, n: number) => acc + n, 0
);

Interfaces & Types

5 snippets

Define custom type shapes

Interface

interface User {
    name: string;
    age: number;
    email?: string;  // optional
}

Type Alias

type ID = string | number;

Union

type Status = "pending" | "approved" | "rejected";

Intersection

type Employee = Person & { employeeId: number };

Extends

interface Admin extends User {
    permissions: string[];
}

Functions

4 snippets

Typed functions and callbacks

Typed Function

function greet(name: string): string {
    return `Hello, ${name}!`;
}

Arrow Function

const add = (a: number, b: number): number => a + b;

Optional Param

function greet(name?: string): string {
    return `Hello, ${name ?? "World"}!`;
}

Function Type

type Callback = (data: string) => void;

Generics

4 snippets

Reusable type-safe components

Generic Function

function identity<T>(arg: T): T {
    return arg;
}

Generic Interface

interface Box<T> {
    value: T;
}

Constraints

function getLength<T extends { length: number }>(arg: T): number {
    return arg.length;
}

Multiple Types

function pair<K, V>(key: K, value: V): [K, V] {
    return [key, value];
}

Utility Types

12 snippets

Built-in type transformations

Partial

type PartialUser = Partial<User>;
// All properties optional
// { name?: string; age?: number; }

Required

type RequiredUser = Required<User>;
// All properties required

Pick

type NameOnly = Pick<User, "name" | "age">;
// Only selected properties

Omit

type NoEmail = Omit<User, "email">;
// All except listed properties

Record

type UserMap = Record<string, User>;
type StatusMap = Record<"pending" | "done", number>;

Readonly

type ReadonlyUser = Readonly<User>;
// All properties readonly

Exclude

type T = Exclude<"a" | "b" | "c", "a">;
// "b" | "c"

Extract

type T = Extract<"a" | "b" | "c", "a" | "f">;
// "a"

NonNullable

type T = NonNullable<string | null | undefined>;
// string

ReturnType

function getUser() { return { name: "John" }; }
type User = ReturnType<typeof getUser>;

Parameters

function greet(name: string, age: number) {}
type P = Parameters<typeof greet>;
// [string, number]

Awaited

type A = Awaited<Promise<string>>;
// string

Classes

3 snippets

Object-oriented programming patterns

Class

class Dog {
    constructor(public name: string) {}

    bark(): string {
        return `${this.name} says woof!`;
    }
}

Private/Public

class User {
    private password: string;
    public name: string;
}

Abstract

abstract class Animal {
    abstract speak(): void;
}

Advanced Types

7 snippets

Complex type manipulations

Type Guard

function isString(x: unknown): x is string {
    return typeof x === "string";
}

if (isString(value)) {
    value.toUpperCase();  // TS knows it's string
}

Discriminated Unions

type Result =
    | { status: "success"; data: string }
    | { status: "error"; error: Error };

function handle(r: Result) {
    if (r.status === "success") {
        console.log(r.data);  // TS knows data exists
    }
}

As Const

const colors = ["red", "green"] as const;
// readonly ["red", "green"]

const config = {
    port: 3000,
    host: "localhost"
} as const;

Template Literal Types

type Event = "click" | "focus";
type Handler = `on${Capitalize<Event>}`;
// "onClick" | "onFocus"

Mapped Types

type Getters<T> = {
    [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number; }

Conditional Types

type IsString<T> = T extends string ? true : false;

type A = IsString<"hello">;  // true
type B = IsString<42>;       // false

Infer Keyword

type UnwrapPromise<T> =
    T extends Promise<infer U> ? U : T;

type A = UnwrapPromise<Promise<string>>;  // string
type B = UnwrapPromise<number>;           // number

More Cheat Sheets

FAQ

Frequently asked questions

What is a TypeScript cheat sheet?

A TypeScript cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in TypeScript. It helps developers quickly look up syntax without searching through documentation.

How do I learn TypeScript quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important TypeScript concepts?

Key TypeScript concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my TypeScript code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your TypeScript code using AI.

Code Conversion Tools

Convert TypeScript to Other Languages

Easily translate your TypeScript code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate TypeScript Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week