Skip to content
Checks TypeScript types match expected values
Branch: master
Clone or download
Latest commit 0a631d2 Mar 25, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src Add `TypeEqual` generic type Mar 25, 2019
.editorconfig
.gitignore . Mar 15, 2019
.travis.yml . Mar 15, 2019
LICENSE
README.md Add `TypeEqual` generic type Mar 25, 2019
package-lock.json 1.1.0 Mar 25, 2019
package.json
tsconfig.json
tslint.json . Mar 15, 2019

README.md

TS Expect

NPM version NPM downloads Build status Test coverage

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 --save

Usage

import { expectType, TypeOf, TypeEqual } from "ts-expect";

expectType<string>(123); // Compiler error!

expectType<TypeOf<number, 123>>(true);
expectType<TypeEqual<"test", "test">>(true);

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:

  • dtslint does type checks via comment directives and inspired this approach of using the compiler
  • tsd-check is a CLI that runs the TypeScript type checker over assertions
  • type-plus comes with various type and runtime TypeScript assertions
  • static-type-assert exposes a similar API surface with some type assertion functions

License

MIT

You can’t perform that action at this time.