typescript / intermediate
Snippet
Enforcing Test Invariants with Assertion Signatures
Assertion signatures use the 'asserts condition' syntax to inform the TypeScript compiler that a function call will throw if a condition is not met, refining downstream types automatically for robust test suites.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class AssertionError extends Error {constructor(message: string) {super(message);this.name = "AssertionError";}}function assertIsDefined<T>(val: T, name: string): asserts val is NonNullable<T> {if (val === null || val === undefined) {throw new AssertionError(`Expected '${name}' to be defined, but received ${val}`);}}function verifyUser(user: { id?: string } | null) {assertIsDefined(user, "user");assertIsDefined(user.id, "user.id");const userId: string = user.id;}
Breakdown
1
function assertIsDefined<T>(val: T, name: string): asserts val is NonNullable<T> {
Declares an assertion function that narrows types in the caller scope upon success.
2
throw new AssertionError(`Expected '${name}' to be defined, but received ${val}`);
Raises an explicit assertion error if the validation fails.
3
const userId: string = user.id;
TypeScript safely narrows 'user.id' from string | undefined to string without casting.