TypeScript · Expert
This snippet uses template literal types and recursive conditional types to extract dynamic path parameters from a string literal at compile time. It demonstrates how TypeScript can parse strings t…
SyntaxData Types
Open snippet →TypeScript · Expert
TypeScript uses structural typing, but sometimes we need nominal typing to prevent accidental mixing of logically different primitives (like different currencies or IDs). Branding 'tags' a type wit…
SecurityBest Practices
Open snippet →TypeScript · Expert
This expert-level snippet demonstrates how to transform a union type into an intersection type. It exploits the fact that function parameters are contravariant, forcing TypeScript to reconcile mult…
Data TypesPerformance
Open snippet →TypeScript · Expert
Introduced in TypeScript 5.2, the 'using' declaration leverages the 'Symbol.dispose' hook to ensure resources like file handles or database connections are cleaned up automatically when the block s…
SyntaxBest Practices
Open snippet →TypeScript · Expert
Stage 3 decorators provide a type-safe way to wrap class members. Unlike older experimental decorators, these use a structured 'context' object containing the member name, private/static status, an…
OOPDesign Patterns
Open snippet →TypeScript · Expert
Assertion signatures use the 'asserts' keyword to tell the compiler that if a function returns normally, a certain condition must be true. This narrows types across the remainder of the containing…
Control FlowFunctions
Open snippet →TypeScript · Expert
The 'satisfies' operator validates that an object matches a type without widening its inferred type. This allows you to keep specific literal information (like knowing 'red' is a tuple) while ensur…
SyntaxBest Practices
Open snippet →TypeScript · Expert
By assigning a variable to the 'never' type in a default branch, you create a compile-time check for exhaustiveness. If a new member is added to the 'Shape' union, the code will fail to compile unt…
Control FlowError Handling
Open snippet →TypeScript · Expert
TypeScript 4.7 introduced explicit variance annotations 'in' and 'out' for generic type parameters. 'out T' marks a covariant position (the type only appears in outputs), 'in T' marks contravarianc…
SyntaxData Types
Open snippet →TypeScript · Expert
Promise.withResolvers (ES2024, TS 5.4+) returns the promise together with its resolve and reject functions without forcing you to capture them inside the executor callback. This avoids the awkward…
Async & ConcurrencyDesign Patterns
Open snippet →TypeScript · Expert
The 'satisfies' operator (TS 4.9+) is the right tool for building test doubles. Unlike a type annotation (': UserRepo'), it does not widen the variable to the interface — so findById keeps its narr…
TestingBest Practices
Open snippet →TypeScript · Expert
The 'const' modifier on a type parameter (TS 5.0+) tells the inference engine to treat the argument as if the caller had written 'as const' — preserving string literals, readonly arrays, and tuple…
FunctionsSyntax
Open snippet →TypeScript · Expert
Implementing Symbol.asyncIterator turns a cursor-driven data source into a first-class for-await-of iterable. The async generator stores the cursor on the call stack rather than in instance fields,…
Async & ConcurrencyDesign PatternsOOP
Open snippet →TypeScript · Expert
Equal compares two types by checking whether two generic function signatures parameterised over them are mutually assignable — strict enough to distinguish `any` from `unknown` and to refuse struct…
TestingDesign Patterns
Open snippet →TypeScript · Expert
AbortSignal.timeout produces a signal that auto-aborts after the given delay, while AbortSignal.any merges multiple signals so the first to abort wins and the combined signal carries that reason. W…
Async & ConcurrencyError Handling
Open snippet →TypeScript · Expert
`reduce<Counts>` pins the accumulator's type so the callback's return value is checked structurally on every branch instead of being widened to `Event | Counts`. Inside the switch, narrowing on the…
Arrays & ListsDesign PatternsBest Practices
Open snippet →TypeScript · Expert
Variadic tuples let you treat a function's parameter list as a generic tuple and peel parameters off one at a time. The Curry mapped type recurses through the tuple: each step returns a unary funct…
Arrays & ListsFunctions
Open snippet →TypeScript · Expert
`await using` (TC39 Explicit Resource Management, supported since TypeScript 5.2) binds an async-disposable to a block scope and invokes its `Symbol.asyncDispose` method when the scope exits — even…
Async & ConcurrencyDesign PatternsError Handling
Open snippet →TypeScript · Expert
TypeScript's structural type system normally treats every `string` as interchangeable, so validated values silently mix with raw input. A branded type tags a primitive with a phantom `unique symbol…
Data TypesSecurityDesign Patterns
Open snippet →TypeScript · Expert
Recursive conditional types combined with variadic tuple spreads let you compute on arrays at the type level — not just at the value level. `Reverse` splits the head off, recurses on the tail, and…
Arrays & ListsData Types
Open snippet →TypeScript · Expert
Example-based tests check single inputs; property-based tests assert invariants over a generated sample space. Modelling a generator as `Gen<T> = () => T` makes them composable through plain functi…
TestingFunctionsDesign Patterns
Open snippet →TypeScript · Expert
`Array<T>` and `T[]` carry no length information at the type level, so a function expecting a 3-vector cannot reject a 2-vector at compile time. The tail-recursive `Tuple<T, N, R>` builder accumula…
Arrays & ListsData Types
Open snippet →TypeScript · Expert
Library authors test runtime behavior with Vitest or Jest, but type-level contracts need their own gate. The `Equal<A, B>` trick exploits the fact that two function types with internal conditionals…
TestingDesign Patterns
Open snippet →TypeScript · Expert
`Promise.all` is fail-fast: one rejection discards every fulfilled value, which is the wrong shape whenever partial success has business meaning (fan-out fetches, batch writes, parallel migrations)…
Async & ConcurrencyError Handling
Open snippet →TypeScript · Expert
This snippet demonstrates how framework authors can extract route parameters dynamically from a path string literal at compile time using TypeScript template literal inference and recursion. The re…
FrameworksSyntaxData Types
Open snippet →TypeScript · Expert
This expert pattern uses opaque tokens with phantom data traits (`_type!: T`) to build a lightweight, fully type-safe dependency injection container without reliance on experimental decorators or m…
FrameworksDesign PatternsOOP
Open snippet →TypeScript · Expert
By mapping generic record types to event names and payloads, this pattern constructs a strongly typed event channel. Listeners automatically receive inferred event payload parameters based on the e…
FrameworksAsync & ConcurrencyFunctions
Open snippet →TypeScript · Expert
This design demonstrates how async middleware composition can be typed in framework engines. Using functional recursive iteration with next handlers ensures controlled contextual transformations ac…
FrameworksDesign PatternsFunctions
Open snippet →TypeScript · Expert
Phantom type parameters attach type-level tags to runtime instances without modifying their underlying data structure. This prevents invalid lifecycle state transitions at compile time in core appl…
FrameworksDesign PatternsBest Practices
Open snippet →TypeScript · Expert
This snippet demonstrates compile-time template literal type recursions to derive dot-notated string paths for deeply nested object structures. It provides complete type safety when reading deeply…
Data TypesSyntax
Open snippet →