typescript / expert
Snippet
Nominal Dependency Registry Typing for Mocked Unit Test Harnesses
Mapped types combined with type inference (`infer`) can transform concrete service interfaces into fully typed mock fixtures while applying nominal branding (`unique symbol`) to prevent unintentional structural assignment errors in test suites.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
declare const mockBrand: unique symbol;type MockedService<T> = {[K in keyof T]: T[K] extends (...args: infer A) => infer R? { (...args: A): R; mockCalls: A[] }: T[K];} & { readonly [mockBrand]: unique symbol };type RegistrySchema = {logger: { log(msg: string): void };database: { query(sql: string): unknown[] };};type MockContainer<T> = {[K in keyof T]: MockedService<T[K]>;};
Breakdown
1
declare const mockBrand: unique symbol;
Declares a unique symbol to establish a nominal brand for test mock objects.
2
[K in keyof T]: T[K] extends (...args: infer A) => infer R
Maps over type properties and inspects function signatures to extract argument tuples and return types.
3
? { (...args: A): R; mockCalls: A[] }
Augment function types with a typed array tracking historic invocation arguments.
4
} & { readonly [mockBrand]: unique symbol };
Intersects the object with a nominal brand token to prohibit standard objects from satisfying mock constraints.