Skip to content

Instantly share code, notes, and snippets.

@TCotton
Last active November 29, 2025 12:20
Show Gist options
  • Select an option

  • Save TCotton/7f3f8702db40d5cc7ff63942576e8118 to your computer and use it in GitHub Desktop.

Select an option

Save TCotton/7f3f8702db40d5cc7ff63942576e8118 to your computer and use it in GitHub Desktop.
branded types
/**
Branding in TypeScript is a technique for creating opaque, nominal, or distinct types even when they
have the same underlying structure.
It’s one of the most useful advanced type tricks in TS, because the language is otherwise structurally typed. **/
// Branding:
// Makes structurally identical types distinct
// Uses phantom fields erased at compile time
// Usually uses unique symbol
// Works with primitives, objects, classes, and generics
// Enforces stronger correctness
// Prevents accidental misuse of domain-specific values
// brand types are too strict and don't allow the full range of unhappy path unit tests
type Redacted<T> = {
readonly __brand: 'Redacted'
readonly value: T
}
function redact<T>(value: T): Redacted<T> {
return { __brand: 'Redacted', value }
}
export function redactKeys<
T extends Record<string, any>,
K extends keyof T & string
>(obj: T, keys: ReadonlyArray<K>): T {
const clone = { ...obj }
for (const k of keys) {
if (k in clone) {
clone[k] = redact(clone[k]) as any
}
}
return clone
}
const anObject = {
a: 1,
b: 2,
c: {
d: 3,
e: 4
}
}
redactKeys(anObject, ['c', 'b'])
// but fine if returning special type, I UUID and not just string
// Generic brand helper (not strictly required, but nice to have)
export type Brand<B, T> = T & { readonly __brand: B };
export type UUID = Brand<"UUID", string>;
export type UUIDv7 = Brand<"UUIDv7", UUID>;
export type UUIDv4 = Brand<"UUIDv4", UUID>;
// Base UUID brand
declare const UUIDBrand: unique symbol;
/**
* Any canonical 8-4-4-4-12 hex UUID string (including nil, max, v1–v8, etc.)
*/
export type UUID = string & { readonly [UUIDBrand]: "UUID" };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment