TS Expect
Checks TypeScript types match expected values.
Why? This is useful for designing type assertions against the TypeScript compiler. It allows you to catch a subset of issues in the compiler before runtime.
Installation
npm install ts-expect --saveUsage
import { expectType, TypeOf } from "ts-expect";
expectType<string>(123); // Compiler error!Examples
export Type = "foo" | "bar";
function validateType(type: string): type is Type {
if (type === "foo") {
expectType<TypeOf<typeof type, Type>>(true); // Compiler error! Forgot `type === "bar"`.
return true;
}
return false;
}
function doSomething(type: Type) {
if (type === "foo") return; // Do something with `foo`.
expectType<never>(type); // Compiler error! Forgot `type === "bar"`.
throw new TypeError(`Unknown type: ${type}`)
}
// Test function signatures.
expectType<TypeOf<[number], Parameters<typeof validateType>>>(false);Prior Works
Some great prior works have been mentioned after publishing this package:
dtslintdoes type checks via comment directives and inspired this approach of using the compilertsd-checkis a CLI that runs the TypeScript type checker over assertionstype-pluscomes with various type and runtime TypeScript assertionsstatic-type-assertexposes a similar API surface with some type assertion functions
License
MIT