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 conditional types to help test your types.
These will resolve to the type true
when they match and false
otherwise.
IsNullable<T>
- Checks ifT
is possiblynull
orundefined
.IsExact<T, U>
- Checks ifT
exactly matchesU
.Has<T, U>
- Checks ifT
hasU
.NotHas<T, U>
- Checks ifT
does not haveU
.IsAny<T>
- Checks ifT
is theany
type.IsNever<T>
- Checks ifT
is thenever
type.IsUnknown<T>
- Checks ifT
is theunknown
type.- More to come...
Use what you prefer:
- The
AssertTrue
,AssertFalse
, orAssert
types. - The
assert
function.
Doing a test:
import type {
AssertFalse,
AssertTrue,
Has,
IsNever,
IsNullable,
} from "https://deno.land/x/conditional_type_checks/mod.ts";
const result = someFunction(someArg);
type _test =
| AssertTrue<Has<typeof result, string> | IsNullable<typeof result>>
| AssertFalse<IsNever<typeof result>>
| Assert<Has<typeof result, number>, true>;
Warning: Do not use an intersection type between checks (ex. Has<string | number, string> & IsNever<never>
) because it will cause everything to pass if only one of the checks passes.
Doing a test:
import {
assert,
IsExact,
} from "https://deno.land/x/conditional_type_checks/mod.ts";
const result = someFunction(someArg);
// compile error if the type of `result` is not exactly `string | number`
assert<IsExact<typeof result, string | number>>(true);
Failure:
// causes a compile error that `true` is not assignable to `false`
assert<IsNullable<string>>(true); // string is not nullable
npm install --save-dev conditional-type-checks