Compile-Time Type Assertion Helpers
Assert type equality at build time with Equal, Expect, IsAny and tiny runtime helpers, catching type regressions during tsc.
Code
export type Equal<Left, Right> =
(<Value>() => Value extends Left ? 1 : 2) extends <Value>() => Value extends Right ? 1 : 2
? true
: false;
export type Expect<Condition extends true> = Condition;
export type IsAny<Value> = 0 extends 1 & Value ? true : false;
export function expectType<Expected>(value: Expected): Expected {
return value;
}
export function expectAssignable<Expected>(value: Expected): void {
void value;
}
export type TypeAssertions = [
Expect<Equal<string, string>>,
Expect<Equal<IsAny<unknown>, false>>,
Expect<Equal<IsAny<any>, true>>,
Expect<Equal<"a" | "b", "b" | "a">>,
Expect<Equal<{ id: number }, { id: number }>>,
];
const user = expectType<{ id: number }>({ id: 1 });
console.log(user.id);
expectAssignable<string | number>("ok");
expectAssignable<string | number>(42);Report a problem with this exampleOpens a pre-filled issue on GitHub.