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…
syntaxdatatypes
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…
securitybestpractices
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…
datatypesperformance
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…
syntaxbestpractices
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…
ooppatterns
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…
controlflowfunctions
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…
syntaxbestpractices
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…
controlflowerrorhandling
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…
syntaxdatatypes
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…
asyncpatterns
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…
testingbestpractices
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,…
asyncpatternsoop
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…
testingpatterns
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…
asyncerrorhandling
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…
arrayspatternsbestpractices
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…
arraysfunctions
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…
asyncpatternserrorhandling
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…
datatypessecuritypatterns
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…
arraysdatatypes
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…
testingfunctionspatterns
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…
arraysdatatypes
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…
testingpatterns
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)…
asyncerrorhandling
Open snippet →