tsafe allows for the unit testing of types, as demonstrated below:
// The following test file is not meant to be executed; it passes only if there are no TypeScript errors.
import { assert, Equals } from "tsafe";
declare function myFunction<T extends string>(arr: T[]): T;
{
const got = myFunction([ "a", "b", "c" ]);
type Got = typeof got;
type Expect = "a" | "b";
// A TS error is present here, as expected
// In this case:
// Got is "a" | "b" | "c"
// and Expect is "a" | "b"
assert<Equals<Got, Expect>>();
}
{
const got = myFunction([ "a", "b", "c" ]);
type Got = typeof got;
type Expect = "a" | "b" | "c";
// ✅ Got and Expect should be the same type
assert<Equals<Got, Expect>>();
}
{
//@ts-expect-error: Passing numbers should not be allowed
myFunction([ "a", 42, "c" ]);
}
{
// This section shows an error expecting expression validity
//@ts-expect-error
myFunction([ "a", "b", "c" ]);
}
{
const got = myFunction([ "a", "b", "c" ]);
type Got = typeof got;
// Validation to ensure that Got is a string type
assert<Got extends string ? true : false>();
}
{
type T = "a" | "b";
type U = string;
// Verifying that T extends U
assert<T extends U ? true : false>();
}
In this code snippet example:
import { assert } from "tsafe/assert";
import type { Extends } from "tsafe";
type Action= { _signature: undefined; }
class Action1 implements Action {
_signature: undefined;
}
class Action2 implements Action {
_signature: undefined;
}
export type ActionsUnion =
| Action1
| Action2;
assert<Extends<Action1, ActionsUnion>>();
Full credit goes to the author of this content.