Menu

TypeScript Cheat Sheet

Last updated

Basic types

The primitive types and how to annotate variables.

OperationSyntax
Stringlet name: string = "Ada";
Numberlet age: number = 25;
Booleanlet ok: boolean = true;
Array of Tlet xs: number[] = [1, 2, 3];
Generic arraylet xs: Array<string> = [];
Tuplelet pair: [string, number] = ["a", 1];
Any (opt out of typing)let x: any = 1;
Unknown (safer any)let x: unknown = JSON.parse(s);
Void (no return)function log(): void { … }
Never (never returns)function fail(): never { throw … }
Null / undefinedlet n: null = null;

Type inference & annotations

When to let TS infer and when to annotate.

OperationSyntax
Inferred from valuelet count = 0; // number
Explicit annotationlet count: number = 0;
Function parameterfunction add(a: number, b: number) { … }
Return typefunction add(a: number, b: number): number { … }
Arrow functionconst sq = (x: number): number => x * x;
Type assertionconst el = input as HTMLInputElement;
Const assertion (literal)const dirs = ["up", "down"] as const;
Non-null assertionel!.focus();

Interfaces

Describe the shape of an object.

OperationSyntax
Declareinterface User { id: number; name: string; }
Optional propertyinterface User { age?: number; }
Readonly propertyinterface User { readonly id: number; }
Method signatureinterface Logger { log(msg: string): void; }
Extend another interfaceinterface Admin extends User { role: string; }
Index signatureinterface Map { [key: string]: number; }
Implement in a classclass Db implements Logger { … }

Type aliases & unions

Name a type and combine types with | and &.

OperationSyntax
Type aliastype ID = string | number;
Object type aliastype User = { id: number; name: string };
Union typetype Status = "idle" | "loading" | "done";
Intersection typetype Admin = User & { role: string };
Literal typetype Yes = "yes";
Nullabletype Maybe<T> = T | null | undefined;
Function type aliastype Handler = (e: Event) => void;

Functions

Typed parameters, returns, and overloads.

OperationSyntax
Optional parameterfunction greet(name?: string) { … }
Default parameterfunction greet(name = "friend") { … }
Rest parametersfunction sum(...ns: number[]): number { … }
Function typelet fn: (a: number) => number;
Callable interfaceinterface Fn { (x: number): number; }
Overload signaturesfunction f(x: string): string; function f(x: number): number; function f(x: any) { return x; }
Void return ignoredconst cb: () => void = () => 42; // ok

Classes

Classes with access modifiers and parameter properties.

OperationSyntax
Declare a classclass User { name: string; }
Constructorconstructor(name: string) { this.name = name; }
Parameter propertyconstructor(public name: string) {}
Public / private / protectedprivate id: number;
Readonly fieldreadonly id: number;
Static memberstatic count = 0;
Getter / setterget name() { return this._name; }
Inheritanceclass Admin extends User { … }
Abstract classabstract class Shape { abstract area(): number; }

Generics

Reusable types parameterized by other types.

OperationSyntax
Generic functionfunction id<T>(x: T): T { return x; }
Call with explicit typeid<string>("hi");
Generic interfaceinterface Box<T> { value: T; }
Generic type aliastype Pair<A, B> = [A, B];
Generic classclass Stack<T> { items: T[] = []; }
Constraint with extendsfunction len<T extends { length: number }>(x: T) { return x.length; }
Default type parameterinterface Box<T = string> { value: T; }
keyof operatortype K = keyof User; // "id" | "name"
Index access typetype Name = User["name"];

Narrowing

Refine a union to a single type at runtime.

OperationSyntax
typeof checkif (typeof x === "string") { … }
instanceof checkif (e instanceof Error) { … }
in operatorif ("name" in obj) { … }
Equality narrowingif (status === "done") { … }
Truthinessif (value) { … }
Custom type guardfunction isUser(x: any): x is User { return "id" in x; }
Discriminated uniontype Shape = { kind: "sq"; size: number } | { kind: "ci"; r: number };
Exhaustiveness with neverconst _: never = shape;

Enums

Named sets of constants.

OperationSyntax
Numeric enumenum Direction { Up, Down, Left, Right }
String enumenum Status { Idle = "IDLE", Done = "DONE" }
Use a valuelet d: Direction = Direction.Up;
Const enum (inlined)const enum Color { Red, Green, Blue }
Union of literals (modern)type Status = "idle" | "done";

Utility types

Built-in helpers that transform existing types.

OperationSyntax
Make all props optionalPartial<User>
Make all props requiredRequired<User>
Make all props readonlyReadonly<User>
Pick a subset of keysPick<User, "id" | "name">
Omit one or more keysOmit<User, "password">
Object with given keysRecord<string, number>
Exclude from a unionExclude<"a" | "b" | "c", "a">
Keep only from a unionExtract<"a" | "b", "a" | "c">
Remove null / undefinedNonNullable<string | null>
Function return typeReturnType<typeof fn>
Function parameter tupleParameters<typeof fn>
Awaited promise typeAwaited<Promise<string>>

Modules

Import and export across files.

OperationSyntax
Named exportexport function add(a: number, b: number) { … }
Default exportexport default class User { … }
Re-exportexport { User } from "./user";
Named importimport { add } from "./math";
Default importimport User from "./user";
Import a type onlyimport type { User } from "./user";
Import everythingimport * as math from "./math";
Triple-slash reference/// <reference types="node" />

tsconfig essentials

The compiler flags worth knowing.

OptionEffect
"strict": trueEnables all strict-mode checks (recommended).
"target": "ES2022"JavaScript version tsc emits.
"module": "ESNext"Module system in emitted output.
"moduleResolution": "bundler"Resolve modules the way modern bundlers do.
"jsx": "react-jsx"Enable JSX for React 17+.
"esModuleInterop": trueCleaner default imports from CommonJS modules.
"skipLibCheck": trueSkip type-checking node_modules (faster builds).
"noEmit": trueType-check only - leave emit to your bundler.

The TypeScript syntax you reach for most, on one page. This TypeScript cheat sheet is a quick reference for everyday TS - basic types, interfaces, type aliases, generics, unions, narrowing, and the built-in utility types.

Everything here is standard TypeScript that compiles with tsc and runs anywhere modern JavaScript does. Copy what you need, or try any snippet live in the TypeScript playground - nothing to install.

TypeScript cheat sheet FAQ

Is this TypeScript cheat sheet free?
Yes. This TypeScript cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up a type, an interface, or a utility type.
What is the difference between an interface and a type alias?
Both can describe the shape of an object, and in most everyday cases they are interchangeable. Interfaces can be re-opened and extended across files (declaration merging), which is useful for library types. Type aliases can name unions, intersections, tuples, and mapped types - shapes you cannot express with interface. A common rule: use interface for public object shapes, and type for unions, tuples, and computed types.
What is the difference between any and unknown?
any opts out of type checking entirely - the compiler will let you do anything to it. unknown is type-safe: you must narrow it (with typeof, instanceof, or a type guard) before you can use it. Prefer unknown for values from external sources like JSON.parse or fetch - it forces you to validate before using.
Do I need to learn JavaScript before TypeScript?
Yes - TypeScript is JavaScript with a type system layered on top, so every JavaScript skill carries over. If you are still building JS fundamentals (arrays, objects, async/await), the JavaScript cheat sheet is a good starting point and Coddy's free JavaScript course covers the same ground interactively.
Can I practice TypeScript online?
Yes. Open the TypeScript playground to run any snippet from this cheat sheet in your browser - nothing to install. When you want structure, learn from the JavaScript landing and apply the types from this page on top.
Coddy programming languages illustration

Learn TypeScript with Coddy

GET STARTED