0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
TypeScript · ExpertSnippet

Recursive Template Literal Type Parsing

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 to build complex object types based on naming conventions like ':param'.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
type ExtractParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? { [K in Param | keyof ExtractParams<Rest>]: string }
: T extends `${string}:${infer Param}`
? { [K in Param]: string }
: {};
const route = "/user/:id/posts/:postId";
type RouteParams = ExtractParams<typeof route>;
// Result: { id: string; postId: string; }
SyntaxData Types
TypeScript · ExpertSnippet

Nominal Typing via Branded Types

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 with a unique property that doesn't exist at runtime but enforces strict separation at compile time.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
type Brand<K, T> = K & { __brand: T };
type USD = Brand<number, "USD">;
type EUR = Brand<number, "EUR">;
const usd = 10 as USD;
const eur = 10 as EUR;
function addUSD(a: USD, b: USD): USD {
return (a + b) as USD;
}
// Error: Argument of type 'EUR' is not assignable to 'USD'
// addUSD(usd, eur);
SecurityBest Practices
TypeScript · ExpertSnippet

Advanced Inference with Contravariant Parameters

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 multiple union members into a single intersection during inference.

snippet.ts
typescript
1
2
3
4
5
6
type UnionToIntersection<U> =
(U extends any ? (k: U) => void : never) extends
((k: infer I) => void) ? I : never;
type Result = UnionToIntersection<{ a: 1 } | { b: 2 }>;
// Result: { a: 1 } & { b: 2 }
Data TypesPerformance
TypeScript · ExpertSnippet

Explicit Resource Management with 'using'

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 scope exits, similar to C#'s using or Python's with.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
class TempFile implements Disposable {
constructor(public path: string) {}
[Symbol.dispose]() {
console.log(`Deleting ${this.path}`);
}
}
function process() {
using file = new TempFile("/tmp/log.txt");
// File is automatically disposed at end of scope
}
SyntaxBest Practices
TypeScript · ExpertSnippet

Contextual Metadata with Stage 3 Decorators

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, and other metadata without requiring 'reflect-metadata'.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
function loggedMethod<This, Args extends any[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>
) {
const methodName = String(context.name);
return function (this: This, ...args: Args): Return {
console.log(`Calling ${methodName}`);
return target.call(this, ...args);
};
}
OOPDesign Patterns
TypeScript · ExpertSnippet

Assertion Signatures for Runtime Guarding

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 scope, reducing the need for nested if-blocks.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
function assertIsString(val: any): asserts val is string {
if (typeof val !== "string") {
throw new Error("Not a string!");
}
}
function process(input: unknown) {
assertIsString(input);
// input is now narrowed to 'string' for the rest of the scope
console.log(input.toUpperCase());
}
Control FlowFunctions
TypeScript · ExpertSnippet

Precise Validation with the 'satisfies' Operator

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 ensuring the object conforms to a general interface.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
type Colors = "red" | "green" | "blue";
type RGB = [number, number, number];
const palette = {
red: [255, 0, 0],
green: "#00ff00",
blue: [0, 0, 255]
} satisfies Record<Colors, RGB | string>;
// palette.red is inferred as [number, number, number], not string | RGB
const redValue = palette.red[0];
SyntaxBest Practices
TypeScript · ExpertSnippet

Exhaustiveness Checking with the 'never' Type

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 until the new case is handled.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
type Shape = { type: "circle" } | { type: "square" };
function getArea(shape: Shape) {
switch (shape.type) {
case "circle": return Math.PI;
case "square": return 1;
default:
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}
Control FlowError Handling