As TypeScript's type system becomes more complex, it's useful to be able to write tests for what a type should be.
This library offers reusable types to do these checks.
These types do the checks:
IsNullableType<T>
- Checks ifT
is possiblynull
orundefined
.IsExactType<T, U>
- Checks ifT
exactly matchesU
.HasType<T, U>
- Checks ifT
hasU
.NotHasType<T, U>
- Checks ifT
does not haveU
.IsNeverType<T>
- Checks ifT
is the never type.- More to come...
They will resolve to the type true
when they match and false
otherwise.
Use either (whichever you prefer);
- The
AssertTrue
orAssertFalse
types. - The
assert
function.
Doing a test:
import { AssertTrue, AssertFalse, HasType, IsNeverType, IsNullableType } from "conditional-type-checks";
const result = someFunction(someArg);
type doTest = AssertTrue<HasType<typeof result, string> | IsNullableType<typeof result>>
| AssertFalse<IsNeverType<typeof result>>;
Warning: Do not use an intersection type in the type parameter for AssertTrue
and AssertFalse
(ex. HasType<string | number, string> & IsNeverType<never>
) because it will cause the assertion to pass if only one of the checks passes.
Doing a test:
import { assert, IsExactType, IsNullableType } from "conditional-type-checks";
const result = someFunction(someArg);
// compile error if the type of `result` is not exactly `string | number`
assert<IsExactType<typeof result, string | number>>(true);
Failure:
// causes a compile error that `true` is not assignable to `false`
assert<IsNullableType<string>>(true); // string is not nullable
npm install --save-dev conditional-type-checks