Compile-Time Type Assertion Helpers

Assert type equality at build time with Equal, Expect, IsAny and tiny runtime helpers, catching type regressions during tsc.

TypescriptCli Tooling

Code

typescriptsnippet
29 lines
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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

1

How the snippet works

Compile-Time Type Assertion Helpers keeps everything in the functions expectType and expectAssignable.

Applying it

expectType is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

(<Value>() => Value extends Left ? 1 : 2) extends <Value>() => Value extends Right ? 1 : 2
? true
: false;

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `expectType`, `expectAssignable` at load time.