0
# Type Checking & Validation
1
2
Runtime type checking and validation utilities for test data and assertions. These functions provide type-safe runtime validation and type guards that integrate seamlessly with TypeScript's type system.
3
4
## Capabilities
5
6
### Is Promise
7
8
Type guard function that checks if a value is Promise-like, providing compile-time type narrowing.
9
10
```typescript { .api }
11
/**
12
* Type guard to check if value is Promise-like
13
* @param candidate - Value to test for Promise-like behavior
14
* @returns Type predicate indicating if value has .then() method
15
*/
16
function isPromise<T = unknown>(candidate: unknown): candidate is PromiseLike<T>;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { isPromise } from "jest-util";
23
24
// Type-safe Promise detection
25
async function handlePotentialPromise(value: unknown) {
26
if (isPromise(value)) {
27
// TypeScript knows 'value' is PromiseLike<unknown> here
28
const result = await value;
29
return result;
30
} else {
31
// TypeScript knows 'value' is not a Promise here
32
return value;
33
}
34
}
35
36
// Jest test helper usage
37
function processTestResult(result: any) {
38
if (isPromise(result)) {
39
return result.then(processTestResult);
40
}
41
42
// Handle synchronous result
43
return validateResult(result);
44
}
45
46
// Generic type parameter usage
47
interface TestData {
48
id: number;
49
name: string;
50
}
51
52
function processTestData(data: unknown): Promise<TestData> | TestData {
53
if (isPromise<TestData>(data)) {
54
// TypeScript knows data is PromiseLike<TestData>
55
return data.then(validateTestData);
56
}
57
58
// TypeScript knows data is not a Promise
59
return validateTestData(data as TestData);
60
}
61
```
62
63
### Is Non-Nullable
64
65
Type guard that checks if a value is not null or undefined, providing compile-time type narrowing to exclude null/undefined.
66
67
```typescript { .api }
68
/**
69
* Type guard to check if value is not null or undefined
70
* @param value - Value to test
71
* @returns Type predicate indicating if value is non-nullable
72
*/
73
function isNonNullable<T>(value: T): value is NonNullable<T>;
74
```
75
76
**Usage Examples:**
77
78
```typescript
79
import { isNonNullable } from "jest-util";
80
81
// Filter out null/undefined values with type safety
82
const testCases: Array<string | null | undefined> = [
83
"test1",
84
null,
85
"test2",
86
undefined,
87
"test3"
88
];
89
90
const validTestCases: string[] = testCases.filter(isNonNullable);
91
// TypeScript knows validTestCases is string[], not (string | null | undefined)[]
92
93
// Safe property access
94
function processTestConfig(config: { name?: string; timeout?: number }) {
95
if (isNonNullable(config.name)) {
96
// TypeScript knows config.name is string, not string | undefined
97
console.log(`Running test: ${config.name.toUpperCase()}`);
98
}
99
100
if (isNonNullable(config.timeout)) {
101
// TypeScript knows config.timeout is number, not number | undefined
102
setTimeout(() => {}, config.timeout);
103
}
104
}
105
106
// Array processing with type narrowing
107
function collectValidItems<T>(items: Array<T | null | undefined>): T[] {
108
return items.filter(isNonNullable);
109
// Return type is automatically inferred as T[]
110
}
111
```
112
113
### Invariant
114
115
Assertion function that throws an error if the condition is falsy, with TypeScript assertion signature for compile-time type checking.
116
117
```typescript { .api }
118
/**
119
* Assertion function that throws if condition is falsy
120
* @param condition - Condition to assert
121
* @param message - Optional error message (default: empty string)
122
* @throws Error if condition is falsy
123
*/
124
function invariant(condition: unknown, message = ''): asserts condition;
125
```
126
127
**Usage Examples:**
128
129
```typescript
130
import { invariant } from "jest-util";
131
132
// Basic assertions
133
function processTestSuite(suite: any) {
134
invariant(suite, "Test suite is required");
135
invariant(suite.name, "Test suite must have a name");
136
137
// TypeScript knows suite and suite.name are truthy here
138
console.log(`Running suite: ${suite.name}`);
139
}
140
141
// Type narrowing with custom messages
142
function validateTestConfig(config: unknown): asserts config is TestConfig {
143
invariant(config, "Configuration is required");
144
invariant(typeof config === "object", "Configuration must be an object");
145
invariant("testPattern" in config, "Configuration must include testPattern");
146
147
// TypeScript knows config has the required properties after these assertions
148
}
149
150
// Runtime type validation
151
interface User {
152
id: number;
153
name: string;
154
email: string;
155
}
156
157
function processUser(data: any): User {
158
invariant(data, "User data is required");
159
invariant(typeof data.id === "number", "User ID must be a number");
160
invariant(typeof data.name === "string", "User name must be a string");
161
invariant(typeof data.email === "string", "User email must be a string");
162
163
// TypeScript understands that data conforms to User interface
164
return data as User;
165
}
166
167
// Test helper usage
168
function expectNotNull<T>(value: T | null | undefined, message?: string): T {
169
invariant(value != null, message || "Expected non-null value");
170
return value; // TypeScript knows this is T, not T | null | undefined
171
}
172
```
173
174
**Error Handling:**
175
176
```typescript
177
// invariant throws Error with provided message
178
try {
179
invariant(false, "This will always fail");
180
} catch (error) {
181
console.log(error.message); // "This will always fail"
182
}
183
184
// Default message is empty string
185
try {
186
invariant(false);
187
} catch (error) {
188
console.log(error.message); // ""
189
}
190
```
191
192
## Type Definitions
193
194
```typescript { .api }
195
// PromiseLike interface (built-in TypeScript)
196
interface PromiseLike<T> {
197
then<TResult1 = T, TResult2 = never>(
198
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
199
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null
200
): PromiseLike<TResult1 | TResult2>;
201
}
202
203
// NonNullable utility type (built-in TypeScript)
204
type NonNullable<T> = T extends null | undefined ? never : T;
205
```