typescript / expert
Snippet
Compile-Time Type Assertions with Equal and Expect
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 structural near-matches. Expect requires its argument to be `true`, so the assertion lives in the type system and turns drift into a build error. The pattern is the standard way to test type-level utilities without running any code.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type Equal<X, Y> =(<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;type Expect<T extends true> = T;type ParseQuery<S extends string> =S extends `${infer K}=${infer V}&${infer Rest}`? { [P in K]: V } & ParseQuery<Rest>: S extends `${infer K}=${infer V}`? { [P in K]: V }: Record<string, never>;// These lines fail to compile if the parser ever regresses:type _t1 = Expect<Equal<ParseQuery<'a=1&b=2'>, { a: '1' } & { b: '2' }>>;type _t2 = Expect<Equal<ParseQuery<''>, Record<string, never>>>;
Breakdown
1
(<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
The closed generic comparison is what makes the check invariant and reliable.
2
type Expect<T extends true> = T;
The constraint `extends true` rejects every result except a literal true.
3
S extends `${infer K}=${infer V}&${infer Rest}`
Template-literal inference splits a query string at the first `&` boundary.
4
? { [P in K]: V } & ParseQuery<Rest>
Builds one key/value object per pair and intersects them as the recursion unwinds.
5
type _t1 = Expect<Equal<ParseQuery<'a=1&b=2'>, ...>>;
Either the parser matches the expected shape exactly or the file stops compiling.