TypeScript code snippets with use cases
30 ready-made code building blocks, sorted by topic.
Error handling
- try / catch / finally β Guard user input or network responses without the program crashing.
- Validating external data (unknown) β Safely turn JSON from files, APIs or forms into typed objects.
- Result type instead of exceptions β Show expected errors (validation, parsing) explicitly in the return type.
Types
- Interface, Type Alias & Intersection β Describe the shape of data, e.g. API responses, forms or database rows.
- Narrowing union types β Process values that can have several types (inputs, API fields).
- Discriminated union with exhaustiveness check β Model states, e.g. loading states, shapes or message types.
- as const and derived types β Define constant lists (status, colors, roles) once and reuse them as a type.
- Custom type guard β Safely distinguish different object types, e.g. events or response variants.
- Named tuples β Multiple return values in a fixed order, e.g. coordinates or [value, error].
Generics
- Generic function β Helper functions that work safely with arbitrary types (first, groupBy, wrap).
- Generics with constraints (extends, keyof) β Functions that only work with certain shapes, or type-safe property access.
- Utility types in practice β Derive update and preview types from a data model instead of maintaining them twice.
- Generic class (stack) β Build reusable data structures: stack, queue, cache, repository.
Advanced
- satisfies for configurations β Check configuration objects or lookup tables without losing their exact types.
- Mapped type with key remapping β Build types derived automatically from a data model (getters, forms, events).
- Conditional type with infer β Derive types from other types, e.g. the element type of an array or the result of aβ¦
- Branded types β Prevent mix-ups: euros vs. dollars, UserId vs. OrderId.
More snippets
- Hello World β A first test of whether the compiler and runtime environment work.
- Variables and Types β Store values and catch type errors early in the process.
- if / else if / else β React differently, e.g. compute grades or price tiers.
- for and for...of loops β Process every element of a list or repeat n times.
- Function with default value β Bundle recurring logic, e.g. greeting texts or calculations.
- Function overloading β A function whose return type depends on the argument type (parse, get, query).
- Working with arrays β Manage collections of values: add, sort, filter.
- Record as a dictionary β Store mappings, e.g. configurations or JSON-like data.
- Class with inheritance β Bundle data and behavior, e.g. users, products, game characters.
- Abstract class and interface β Define shared behavior and force subclasses to implement it.
- Read and write a file (Node.js) β Save and load logs, configurations or text data.
- Typed API request (fetch) β Load data from a web API and process it further in code using types.
- tsconfig.json for a Node project β Start a new project with strict but practical compiler settings.