1.0.2 • Published 2 years ago

type-assert-tool v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

type-assert-tool

Utility type to assert your TypeScript type.

Usage

import { AssertIs, AssertSub, TestSuite } from "type-assert-tool";

type MyAwesomeType<T = string> = T extends string ? `Hello, ${T} !` : "Bye.";

interface MyAwesomeTypeTest extends TestSuite {
  result1: AssertIs<MyAwesomeType<'world'>, "Hello, world !">;
  result2: AssertIs<MyAwesomeType<number>, "Bye.">;

  // Property 'result3' of type '[actual_type: "Bye.", is_not: "Bye bye"]' is not assignable to string index type 'AssertSuccess'.
  result3: AssertIs<MyAwesomeType<number>, "Bye bye">;

  "you can put cases into a section": {
    pattern1: AssertIs<MyAwesomeType<''>, "Hello,  !">;
    pattern2: AssertSub<MyAwesomeType, string>;

    "nested section": {
      result: AssertSub<"Hello", string>;
    };
  };
}

Try this in Playground!

API

TestSuite

You can write "TypeScript type test" extending this type. For example:

interface YourTestCases extends TestSuite {
  // write test cases as properties
}

There are no restrictions on the property names in the sub interface. However, TestSuite enforces as the sub interface's properties should be assignable to type AssertSuccess .

AssertIs<Actual, Expected>

Test equality between type Actual and type Expected . Only if succeeded, this type returns type AssertSuccess .

AssertSub<Actual, Expected>

Test whether type Actual type is a sub type of type Expected . Only if succeeded, this type returns type AssertSuccess .

Motivation

TypeScript's capabilities of type operations are amazing. TypeScript has powerful features such as Mapped Types, Conditional Types, Recursive Types, and Template Literal Types.

I needed a way to make sure that the composite types I created using these features would work as expected. I created this utility because I wanted to write tests for composite types in the same way I write unit tests for functions.

Similar repositories

  • ts-expect provides function to assert type of your "values".

License

MIT

1.0.2

2 years ago

1.0.1

3 years ago

1.0.0

3 years ago