On this page
Building Type-Level Utilities & Branded Types
Prev: Type-Safe API Clients & Runtime Validation | Up: tutorials | Next: index
Rel: Conditional & Mapped Types, Readonly
Ref: TypeScript Handbook โ Type Manipulation
Tags: #public #web #typescript #tutorials #patterns
Contents
Recursive DeepReadonly<T>
type DeepReadonly<T> = T extends (...args: unknown[]) => unknown
? T
: T extends readonly (infer U)[]
? readonly DeepReadonly<U>[]
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
Branded (Nominal) IDs in a Structural Type System
Prevent accidentally passing an OrderId where a UserId is expected โ with zero runtime overhead โ by intersecting a primitive with a unique phantom brand property:
declare const brand: unique symbol;
type Brand<T, Name extends string> = T & { readonly [brand]: Name };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
const asUserId = (id: string) => id as UserId;
function loadUser(id: UserId) {
return id;
}
const uid = asUserId("u_123");
loadUser(uid); // OK
// loadUser("o_999" as OrderId); // Compile-time error!
Linked from
Related notes
- tuts/typescript/tutorials Linked here; links to this page; shared tags: #tutorials, #typescript, #web
- tuts/typescript/tutorials/type_safe_api_clients_and_validation Linked here; links to this page; shared tags: #tutorials, #typescript, #web
- tuts/typescript/type_system/conditional_and_mapped_types Linked here; shared tags: #typescript, #web
- tuts/typescript/utility_types/object_transforms/Readonly Linked here; shared tags: #typescript, #web
- tuts/index Linked here
- tuts/typescript/tutorials/discriminated_unions_and_state_machines shared tags: #patterns, #tutorials, #typescript, #web
- tuts/css/tutorials shared tags: #tutorials, #web
- tuts/css/tutorials/box_model_and_formatting_contexts shared tags: #tutorials, #web
- tuts/css/tutorials/cascade_specificity_and_inheritance shared tags: #tutorials, #web
- tuts/css/tutorials/modern_layout_flexbox_and_grid shared tags: #tutorials, #web