TypeScript Cheatsheet — Quick Reference
A quick reference for TypeScript 5 syntax, the type system, and the most common idioms — covers about 80% of day-to-day usage.
TypeScript TypeScript 5.x
ECMAScript + types · Multi-paradigm, structured · Static (gradual) typing on top of JS
Recommended Learning Path
First, set up your compile environment (tsc/tsconfig) and understand that TS is a superset of JS → master basic type annotations, union types, and interfaces → go deeper into the type system (generics, type guards, type operations) → organize code with classes and modules → handle async and DOM/Node types → finally look up build config, testing, and debugging as needed. The FAQ section is good to revisit to avoid pitfalls.
1.Hello World and Build Environment
Compile and run TypeScript; understand tsc, tsconfig, and the type-checking pipeline.
Minimal Program
TS is a superset of JS: any valid JS is valid TS. After adding type annotations, tsc compiles it to JS.
tsc Compile
tsc compiles .ts to .js. --noEmit only type-checks without output, --watch watches for changes, --strict enables strict checks.
tsconfig.json
tsconfig.json configures compilation: target, module, strict, outDir. npx tsc reads it automatically.
Run TS Directly
Use tsx/ts-node to run TS directly without compiling first. Node 22 supports --experimental-strip-types natively.
Strict Mode
strict: true turns on all strict checks: null checks, implicit any errors, unused-variable warnings. Required for new projects.
TS vs JS Relationship
TS type-checks at compile time; the compiled JS has no type info. Types exist only at compile time and are erased at runtime.
Dependencies and Type Packages
Libraries need type definitions. @types/* is the DefinitelyTyped community type package. typescript is the compiler tool dependency.
Editor Integration
VS Code has built-in TS support: hover to see types, red squiggles for errors, autocomplete, refactoring. Error messages display inline.
2.Variables and Type Annotations
Type annotations, type inference, union types, any/unknown, and type assertions.
Type Annotations
Annotate a type with `: Type` after the variable name. Once annotated, the type is fixed; assigning another type is a compile error.
Type Inference
TS infers types from initial values; most cases need no explicit annotation. Use an explicit interface for complex types.
Union Types
`|` denotes a union type: `string | number` means either. Accessing members requires a type guard first.
any vs unknown
any disables type-checking (avoid); unknown means unknown (usable only after a guard). Use unknown for safe handling of external data.
Type Assertions
`as` asserts to the compiler that you know better. It doesn't change runtime; it's a compile-time declaration. Overuse hides errors.
Non-null Assertion
The `!` suffix asserts a value is non-null/undefined. Use only when sure, or it may crash at runtime.
Literal Types
Literal types narrow to specific values: 'up', 42, true. Pair with unions to enumerate options.
Destructuring and Types
Destructuring preserves types. Destructured function parameters require annotating the whole parameter object type.
3.Type System
Primitive types, object/array/tuple types, interfaces, generics, type aliases, and type operations.
Primitive Types
The set of primitive types: string, number, boolean, null, undefined, void, symbol, bigint.
Arrays and Tuples
`number[]` for arrays, `[string, number]` for tuples (fixed length and order), `readonly` for read-only arrays.
Object Types
Object types describe a shape: properties, optional `?`, read-only `readonly`, method signatures.
interface vs type
`interface` defines an object shape (extendable); `type` aliases are more flexible (union/intersection/tuple). Prefer interface day-to-day.
Enums
`enum` is a named constant set: numeric, string, or const enum. String enums are more common.
Generics
Generics parameterize types: T is a type parameter. Reuse across functions/classes/interfaces; resolved at compile time.
keyof and Indexing
`keyof` gets a union of object keys, `T[K]` indexes, mapped types. The core tools of type operations.
Built-in Utility Types
Mapped types like Partial/Omit/Pick/Record/Exclude/ReturnType simplify common transformations.
Template Literal Types
Template string syntax to construct string types. Combine with unions to generate permutations. Type-level string parsing.
4.Type Guards and Nullability
Type guards, type narrowing, optional chaining, null handling, and reference semantics.
Type Guards
`typeof`, `instanceof`, `in` narrow union types. Types automatically narrow inside the branch.
Type Narrowing
After a guard, the type narrows in the scope. Null checks and truthy checks both narrow.
Discriminated Unions
Discriminated unions: share a discriminator (kind/type); after `switch` the type narrows precisely. Useful for state machines.
Optional Chaining and Nullish Coalescing
`?.` safe access, `??` nullish fallback, `??=` default assign. Chained deep access without null crashes.
null and undefined
Under strictNullChecks, null/undefined cannot be assigned to plain types. You need an explicit union or handling.
Reference Semantics
TS does not change JS reference semantics: objects are shared by reference, arrays shallow-copy. Types just describe the shape.
Custom Type Guards
The `is` keyword declares a function as a type guard: returns boolean and narrows the parameter. Common for filtering arrays.
Assertion Functions
`asserts` declares an assertion function: returns void but narrows the type after the call. Throws to interrupt.
5.Control Flow
Branches, loops, switch statements, and their interplay with type narrowing.
if / else
`if`/`else` branches with type guards. The condition expression narrows the variable type.
switch and Exhaustiveness
`switch` handles discriminated unions. The `default` branch uses `never` to check all cases are covered.
Loops
`for`/`for...of`/`while` for iteration. Use `for...of` to iterate arrays; use `for` or `entries` when you need the index.
Ternary and Types
The two sides of a ternary form a union. When branches return different types, the result is a union type.
break and continue
`continue` skips the current iteration, `break` exits, labeled `break`/`continue` control nested loops.
Early Return
Guard clauses return early to reduce nesting. After a null check the type narrows.
do...while
`do...while` runs once before testing. Use for loops that must run at least once. Types don't participate.
Object Iteration
`Object.keys` iterates object keys. Asserting `keyof` keeps it type-safe. Use `Object.values` to iterate values.
6.Functions
Function types, optional and default parameters, overloads, rest parameters, and this.
Function Types
Function type annotation: parameter types and return type. Arrow function types are equivalent to function declarations.
Optional and Default Parameters
`?` for optional parameters, `=` for default. Defaults imply optional. Optional parameters come after required ones.
Rest Parameters
`...rest` collects a variable number of arguments into an array. Rest parameters need an array type annotation.
Overload Signatures
Overloads: multiple signature declarations plus one implementation. Calls match by signature. Use to constrain return types per parameter shape.
Generic Functions
Generic parameter constraints: `T extends ...`. Constraints limit the type and expose its members.
this Type
The `this` parameter annotates the `this` type. Method chains return `this` to enable chaining. Arrow functions don't bind `this`.
Callbacks and Function Parameters
Callbacks as parameters: annotate with a function type. Type inference for array higher-order functions like map/filter/reduce.
Function Constraint Techniques
Parameter-union narrowing, optional callbacks, return inference. Prefer interfaces over concrete classes for function parameters.
7.Strings
Template strings, common methods, regex, and character handling.
Template Strings
Backtick template strings: `${}` for interpolation, multi-line preserved. The type is still `string`.
Common Methods
`slice`/`substring` for substrings, `toUpperCase` for case, `split` to split, `includes`/`startsWith` to query, `replace` to replace.
Template Literal Types
Type-level template strings: `${}` concatenates types. Use `infer` to extract string structure.
Characters and Code Points
`length` counts UTF-16 code units (emojis count as two). Iterate code points with `for...of` / `Array.from`.
Regex
`RegExp` for matching and replacing. `match` returns a capture-group array; `matchAll` iterates globally. The type-level `RegExp` is fixed.
Locale and Comparison
`localeCompare` for locale comparison, `toLocaleLowerCase` for locale case, `Intl` for formatting numbers and dates.
Escape Characters
String escapes: `\n` newline, `\t` tab, `\\` backslash, `\u` code point. Escape inside single or double quotes.
Reverse and Compare
Reverse a string with split/array, trim whitespace, dedupe. Compare with `localeCompare` or canonical comparison.
8.Collections and Objects
Arrays, objects, Map/Set, and immutable update patterns.
Array Operations
`push`/`pop` at the tail, `unshift`/`shift` at the head, `splice` insert/remove, `slice` copy, `includes`/`indexOf` to query.
map / filter / reduce
Functional iteration: `map` to transform, `filter` to filter, `reduce` to aggregate, `find` to find, `every`/`some` to test. Returns a new array, never mutates the original.
Object Operations
Spread and merge `{...a, ...b}`; `Object.keys`/`values`/`entries` to iterate; `keyof` for typed keys.
Map
`Map` maps any key: set/get/has/delete/size. Preserves insertion order; O(1) lookup.
Set
`Set` deduplicates: add/delete/has/size. Use to dedupe arrays, compute unions/intersections.
Immutable Updates
Update with spread/copy rather than in place. Replace objects, add/remove items, and return a new reference. Common in React state.
Tuples and Record
Tuples are fixed-length; `Record` is a key-value map. Use `as const` to make object literals constants.
WeakMap / WeakSet
`WeakMap`/`WeakSet` require object keys and hold them weakly. Don't prevent GC. Use for metadata caches or side effects.
9.Performance and Memory
Memory under garbage collection, large data, string optimization, and monitoring.
Garbage Collection
TS/JS has GC; no manual free. Objects are collected when no longer referenced. Beware closures keeping long-lived objects alive.
Large Arrays
For large arrays consider TypedArray or streaming. `filter`/`map` allocate new arrays; a single loop is cheaper.
String Memory
Strings are immutable; concatenation creates new strings. For heavy concatenation, use array `join` or templates. Strings are interned.
WeakRef and Caching
`WeakRef` holds a weak reference that doesn't prevent GC; `WeakMap`/`WeakSet` keys are weak. Use weak containers for caches or side effects.
Performance Tips
Avoid `any` slowing optimization, reduce reallocations, cache results. V8 optimizations depend on stable object shapes.
Memory Monitoring
Node memory: `process.memoryUsage()`, `--max-old-space-size`. In the browser, the Performance API.
Closures and Memory
Closures hold outer variables, prolonging their lifetime. Watch for closure traps in loops. Release references.
TypedArray and Binary
TypedArray for binary numerics: `Uint8Array`/`Float64Array`. Views share the underlying buffer.
10.Classes and OOP
class, access modifiers, inheritance, abstract classes, and generic classes.
class Basics
class syntax: fields, constructor, methods. Fields can be annotated with types and visibility.
Access Modifiers
`public`, `private`, `protected`, `readonly`. All are compile-time checks.
Inheritance and override
`extends` to inherit, `super()` to call the parent constructor, `override` to override a method. A subclass is-a parent.
Abstract Classes and Interfaces
Abstract classes can't be instantiated; abstract methods must be implemented by subclasses. Interfaces constrain shape. Abstract classes can have implementations.
implements
`class implements Interface`: the class must satisfy the interface's shape. A class can implement multiple interfaces.
Generic Classes
Generic classes: type parameters on fields and methods. Constraints narrow the generic range.
getter / setter
`get`/`set` accessors wrap field reads/writes. Add validation and computed logic.
Static Members
`static` defines class-level fields and methods. Static members don't depend on instances. Use `static` for factories and constants.
11.Exception Handling
throw/try-catch, error types, custom errors, and async errors.
throw / try-catch
`throw` raises an error, `try-catch` catches it, `finally` runs cleanup. The `catch` variable defaults to `unknown` and needs narrowing.
Custom Errors
Extend `Error` to define a custom error class. Carry extra info. The error name distinguishes the type.
Common Error Types
Error base class: `TypeError`, `RangeError`, `ReferenceError`. Test with `instanceof`.
Async Errors
An `async` function's `throw` becomes a rejected Promise. Catch with `try-catch` on `await`, or with the `.catch` chain.
Error Boundaries
Module boundaries catch and convert error types. Wrap third-party errors uniformly. Don't let errors escape and crash.
Error Handling Patterns
Return a result for predictable errors, throw for unexpected ones. Result style (`ok`/`err`) and `throw` each have their place.
Error Message Quality
Error messages should include context: what, where, how to fix. Custom errors carry fields.
Unhandled Rejections
An uncaught rejected Promise fires `unhandledrejection`. Add a top-level fallback to avoid silent failures.
12.Input and Output
console output, Node file/stream, fetch networking, and typed JSON.
console Output
`console.log`/`info`/`warn`/`error`, template output, `%o` formatting, groups and counts.
fetch Networking
`fetch` for async requests. `await` the response, parse JSON, handle errors, assert the result type.
Node Files
`fs/promises` for async read/write. `readFile`/`writeFile`/`mkdir`/`readdir` return Promises.
JSON and Types
`JSON.parse`/`stringify` for serialization. `parse` results need a guard; `stringify` ignores functions.
Stream Processing
`ReadableStream`/Web Streams for large responses. Read progress, process chunk by chunk.
Environment Variables and Arguments
Node reads `process.argv` / `process.env`. Argument parsing; narrow environment variable types.
Browser Web APIs
Types for `localStorage`/`sessionStorage`, `navigator`, `WebSocket`. Stored values need serialization.
File Reading
`input[type=file]` to get a `File`, `FileReader` to read text/DataURL, object URL for preview.
13.Common Pitfalls
The most common day-to-day pitfalls and the correct way to write things.
Overuse of any
`any` disables type checks and hides real errors. Prefer `unknown` plus a guard.
Nullish Checks
`!!` for truthy, `== null` for both null and undefined, check array length. Don't treat `0` or `''` as empty.
Async Misuse
Async functions always return a Promise. Forgetting `await` leaks a Promise. `forEach` does not await async work.
Equality Comparison
`===` for strict equality. `NaN !== NaN`. Objects compare by reference. Deep compare manually or with a library.
null vs undefined Confusion
`null` is intentional emptiness, `undefined` is unassigned. Under strictNullChecks handle them separately. Optional chaining vs assertion.
Lost this
`this` becomes `undefined` in callbacks. Bind with arrow functions or explicit `.bind`. Class-field arrow functions are common.
Narrowing Failure
Property accesses can lose narrowing. Destructure to keep the narrowed value. Reassigning a parameter widens the type.
Exhaustiveness Check
Use `never` in the `default` of a discriminated union. Adding a new case without handling it becomes a compile error.
Copy and Modify
Arrays/objects share references by default. Copy before updating. `sort` mutates in place.
14.Concurrency and Async
Promise, async/await, Worker threads, and the event loop.
Promise
Promise represents an async result. `then` chain, `catch` for errors, `finally` for cleanup. Annotate as `Promise<T>`.
async / await
Async functions return a Promise. `await` unwraps it. Catch errors with `try-catch`. Top-level `await` needs ESM.
Parallel and Race
`Promise.all` waits for all, `allSettled` waits for all (including failures), `race` takes the first to settle, `any` takes the first to succeed.
Worker Threads
Web Worker / Node `worker_threads` for parallel compute. `postMessage` to communicate; `transferable` to transfer ownership.
Event Loop
Synchronous code runs first; microtasks (Promise) before macrotasks (setTimeout). Blocking stalls everything.
Generators
`function*` is a lazy generator. `yield` pauses and resumes. Annotate as `Generator`.
Async Iterators
`for await...of` iterates async data sources. `async function*` for async generators. Stream-friendly consumption.
Concurrency Limit
Limit the number of concurrent async tasks. Batch, semaphore, or `p-limit`. Don't overwhelm resources.
15.Networking and Modules
Module system, import/export, fetch, and typed API wrappers.
ES Modules
`import`/`export` for static import/export. Use `export type` for TS types. Modules isolate scope.
Type-only Imports
`import type` imports only types; erased at compile time. Avoids runtime dependencies and circular references.
Typed API Wrappers
Wrap `fetch` to return strong types. Validate responses; handle errors uniformly. Generic request function.
Node HTTP Servers
`node:http` or frameworks (Express/Fastify). Typed request/response. Route handling.
DOM Types
`document.getElementById` return type, event types, HTML element type mapping.
URL and Parameters
`URLSearchParams` builds a query string; `URL` parses. Type-safe parameter reads.
WebSocket
WebSocket is bidirectional. `onmessage` event, generic data, `readyState`.
Headers and Auth
Type-safe `Headers` setup. `Authorization: Bearer ...`, `Content-Type`. Inject via an interceptor.
16.Date and Time
The Date object, timestamps, formatting, and time zones.
Date Basics
`Date` constructor, `getFullYear`/`getMonth`/`getDate` reads, `set*` writes. Months start at 0.
Timestamps
`getTime()` ms timestamp, `Date.now()`, `Date.parse`. Compare dates via timestamps.
Formatting
`toISOString` for UTC, `toLocaleDateString` for local, `Intl.DateTimeFormat` for custom.
Time Zones
Timestamps are UTC milliseconds; formatting applies the local time zone. Use `Intl` with the `timeZone` option to specify a zone.
Timers
`setTimeout` for delay, `setInterval` for periodic, `clearTimeout` to cancel. Return type is `number`.
Durations and Intervals
Subtract two timestamps to get milliseconds. Use timestamps for range checks. Avoid `setInterval` drift.
Date Libraries
dayjs/date-fns provide clear APIs and time-zone handling. Small and immutable. Reach for a library for complex time zones.
High-Resolution Timing
`performance.now()` is millisecond-resolution, monotonic, unaffected by system time changes. Use for performance measurement.
17.Process and System
Node processes, CLI tools, standard streams, and running built artifacts.
Node Process
The `process` global: `argv` args, `env` environment, `exit` code, `stdout`/`stderr` streams.
CLI Tools
Writing a CLI: parse args, help output, exit code. Shebang makes the script executable.
Standard Streams
`stdin` reads input, `stdout` writes output, `stderr` for errors. `readline` for interaction. Piped data.
Running Compiled Output
After `tsc`, run `node dist/main.js`. Register a command via `package.json` `bin`. Type declaration `.d.ts`.
Execute System Commands
`execFile` to run an external command, `spawn` for streaming. `child_process` types. Escape carefully to avoid injection.
Exit Codes
`0` success, non-zero failure. Convention: `1` general error, `2` usage error. CI scripts rely on exit codes.
npm scripts
`package.json` `scripts` orchestrate commands. `pre`/`post` hooks, chain with `&&`, parallel with `&`. Common in build chains.
Config and Environments
`dotenv` loads `.env`. Typed config object, runtime validation. Config separated from code.
18.Regex and Text Processing
Regex syntax, flags, typed matching, and text-processing idioms.
Regex Syntax
Literal `/.../` or `RegExp` constructor. Character classes, quantifiers, groups, anchors.
Flags
`g` global, `i` case-insensitive, `m` multiline, `s` dot matches newline, `u` Unicode, `y` sticky.
Match and Extract
`match` returns an array (full match + capture groups), `matchAll` iterates globally, `match` returns `null` on failure (check it).
Replace
`replace` with string/function. `$1` capture references; global `g` replaces all. Function replacement handles logic.
Validation Idioms
Anchor whole matches with `^...$`. Common patterns for numbers, emails, URLs. `test` returns boolean.
Regex Performance
Avoid catastrophic backtracking: nested quantifiers. Pre-compile regexes. Mind `lastIndex` with the `g` flag.
Common Regex Pitfalls
Literals need escapes, the `g` flag has `lastIndex` state, greedy matching, and `\` in strings is double-escaped.
Common Patterns
Common regex snippets: ID numbers, phones, colors, dates, etc. For business format validation.
19.Build and Tooling
tsconfig, bundlers, linting/formatting, testing, and CI.
tsconfig in Depth
Common compiler options: `moduleResolution`, `declaration`, `noUnusedLocals`, `esModuleInterop`, `paths` alias.
Bundlers
Vite/Webpack/Rollup for bundling. Vite is the default for TS/frontends. For libraries, use tsup/Rollup to emit ESM+CJS.
Lint and Formatting
ESLint for rules, Prettier for formatting. `ts-eslint` provides type-aware rules.
Testing
Vitest/Jest for unit tests. `describe`/`it`/`expect`. Types and runtime are separate. Test TS directly.
CI and Deployment
CI stages: type check, lint, test, build. `tsc --noEmit` blocks type errors.
Debugging
sourceMap + Node `--inspect` breakpoint debugging. `console` debugging, type assertions to help.
Publishing to npm
Publishing a library: `files` controls content, semantic `version`, `main`/`types`/`exports` entry points. Build before publishing.
Monorepo Config
npm/pnpm workspaces for multi-package repos. Shared dependencies, inter-package references, unified scripts.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained cheatsheet for TypeScript 5.x, covering the type system and core language features that make up roughly 80% of real-world use. The content leans toward modern idioms: interfaces and type aliases, generics, union and intersection types, type narrowing, literal types, keyof/typeof, mapped and conditional types, and their interplay with async programming. TypeScript was released by Microsoft in 2012 as a superset of JavaScript, adding static type-checking at compile time and dramatically improving maintainability for large codebases — today it's the mainstream choice for front-end engineering. The 19 sections each focus on one theme: basic syntax, variables and type inference, the type system, references and value semantics, control flow, functions and overloads, strings and templates, collections, memory and type erasure, classes and interfaces, error handling, I/O, common pitfalls, concurrency (async types), networking, time, processes, regex, and build tools (tsc/tsconfig). Each sub-section pairs a concept with a directly copy-pastable snippet. All code and text render locally in your browser; no data leaves your device. For the authoritative reference, see the official TypeScript handbook.
Version 2.1.0