
TypeScript code examples
Browse 253 TypeScript code examples across 26 topics, including object types, discriminated unions, generic functions.
Jump to a topic
Object types
Discriminated unions
Generic functions
Tuple types
- Destructure named coordinates
- Calculate a point magnitude
- Return a translated point
- Append an item to a tuple
- Prepend a label to a tuple
- Use an optional tuple entry
- Accept a nonempty numeric series
- Represent a tuple of heterogeneous pairs
- Type a function argument list
- Preserve coordinates in a readonly tuple list
Literal unions
- Derive a union from const data
- Check a string against literal values
- Require a label for every state
- Exclude the terminal state
- Extract just the terminal state
- Type a status transition map
- Preserve exact return literals
- Define a subset of statuses
- Use a status as a mapped key
- Derive array length as a literal
Optional and nullable values
- Read a nested optional field
- Keep a valid zero score
- Narrow nullable scores with a predicate
- Distinguish absent from present contact
- Default an omitted argument
- Call an optional callback
- Default an optional destructured property
- Require an optional contact shape
- Return a nullable lookup result
- Fill a missing field immutably
Unknown input
- Narrow an unknown string
- Find finite numbers in mixed input
- Recognize arrays of numbers
- Recognize an object with a numeric ID
- Narrow an Error with instanceof
- Guard a boolean field
- Parse JSON into unknown first
- Check a nullable input explicitly
- Narrow an unknown symbol
- Handle a caught non-Error value
Mapped types
Template literal types
- Compose a typed permission string
- Type a CSS pixel length
- Constrain environment variable prefixes
- Require a slash-prefixed route
- Create uppercase event names
- Create title-case action labels
- Create getter names from keys
- Derive a suffix with infer
- Represent numeric IDs as strings
- Enforce a filename extension
Conditional types
Function signatures
Typed collections
- Initialize a typed Map
- Safely read a missing key
- Initialize a typed Set
- Index records by stable key
- Convert typed entries to a dictionary
- Type an accumulator for group totals
- Read entries from a readonly map
- Read membership from a readonly set
- Store object-keyed metadata
- Track visited objects by identity
Interfaces and classes
- Implement a named object interface
- Extend an interface
- Use a readonly constructor field
- Encapsulate a private field
- Use a protected base method
- Override an inherited method
- Implement an abstract method
- Construct an instance from a typed constructor
- Infer a constructor's argument types
- Derive an instance type
Async typing
- Annotate an async return value
- Infer a resolved record type
- Await a heterogeneous promise tuple
- Narrow settled promise results
- Return a typed fallback on rejection
- Accept a sync or async loader
- Transform a promised record
- Sequence asynchronous typed work
- Yield values from an async generator
- Return a typed result from a caught rejection
State machines
Recursive data
Branded values
- Create a positive ID at a validation boundary
- Convert seconds to branded milliseconds
- Parse a normalized slug
- Separate display labels from IDs
- Add amounts in the same currency
- Define a fixed-length hexadecimal token
- Read a value through a branded map key
- Validate a bounded percentage
- Validate a nonempty label
- Reject fractional cent amounts
Typed events
- Bind an event name to its payload
- Define typed event listeners
- Build a correlated event union
- Accept a single payload field
- Represent event tuples
- Define a typed event envelope
- Record event-specific histories
- Select a handler by lifecycle stage
- Derive listener names from event names
- Use a type-only event import shape
Type-safe configuration
- Override a single option with satisfies
- Keep a literal config mode
- Select deployable settings
- Collect configuration keys for a form
- Check a mode from environment text
- Merge tags without duplicates
- Derive a partial config setter
- Enforce a mutually exclusive config source
- Type a full environment matrix
- Describe a deep partial update for nested flags
Form handling
- Build a field-error map
- Check a typed form field
- Parse a numeric input strictly
- Convert checkbox text to a boolean
- Serialize form values for transport
- Track touched fields
- Apply a typed input change
- Build a typed field descriptor union
- Clear a field error immutably
- Validate a field with a reusable rule
Typed pagination
- Check for another page
- Read a page's item type
- Map a page while preserving its cursor
- Collect items across pages
- Make an empty page of a known type
- Take the first page of records
- Read a cursor as a nonnegative offset
- Filter a page without losing metadata
- Deduplicate paged records by ID
- Construct a final page from an iterable
Sorting and indexing
Binary and numeric data
- Project records into a Float32Array
- Calculate a typed running sum
- Find a numeric sample range
- Compute the slope between samples
- Scale samples using a typed transform
- Select an interval by time
- Find the nearest timestamp
- Compute a mean for an optional series
- Create typed threshold buckets
- Write a signed sample to a DataView
Typed routes
- Infer route names from a registry
- Infer a literal HTTP method
- Build a route with a required parameter
- Encode a typed query object
- Select routes matching a method
- Build a typed redirect result
- Represent a validated response union
- Decode an optional route segment
- Match route templates by segments
- Create a route-specific body contract
Immutable updates
- Append to a readonly list
- Replace a matching record immutably
- Remove a record by key
- Insert at a known position
- Replace an item using with
- Reverse without mutating a readonly source
- Update a nested dictionary entry
- Freeze a public snapshot
- Return an unchanged reference for a no-op
- Copy a mutable working list from an iterable