0
# Programmatic API
1
2
Main testing function and diagnostic formatter for integration with testing frameworks and custom workflows. Provides programmatic access to TSD's type checking capabilities.
3
4
## Capabilities
5
6
### Main TSD Function
7
8
The primary function for programmatically running type definition tests.
9
10
```typescript { .api }
11
/**
12
* Type check the type definition of the project
13
* @param options - Configuration options for type checking (defaults to {cwd: process.cwd()})
14
* @returns Promise resolving to array of diagnostics
15
*/
16
function tsd(options?: Options): Promise<Diagnostic[]>;
17
18
interface Options {
19
/** Current working directory of the project to retrieve diagnostics for */
20
cwd: string;
21
/** Path to the type definition file you want to test */
22
typingsFile?: string;
23
/** Array of test files with their path */
24
testFiles?: readonly string[];
25
}
26
```
27
28
**Usage Examples:**
29
30
```typescript
31
import tsd from "tsd";
32
33
// Basic usage - test current directory
34
const diagnostics = await tsd();
35
36
console.log(`Found ${diagnostics.length} issues`);
37
38
// Custom working directory
39
const diagnostics = await tsd({
40
cwd: "/path/to/my-project"
41
});
42
43
// Specific typings file
44
const diagnostics = await tsd({
45
cwd: "/path/to/project",
46
typingsFile: "dist/custom.d.ts"
47
});
48
49
// Custom test files
50
const diagnostics = await tsd({
51
cwd: "/path/to/project",
52
testFiles: ["tests/types/*.test-d.ts", "src/**/*.test-d.ts"]
53
});
54
55
// Check for errors
56
const hasErrors = diagnostics.some(d => d.severity === "error");
57
if (hasErrors) {
58
process.exit(1);
59
}
60
```
61
62
### Diagnostic Formatter
63
64
Format diagnostics for human-readable output, matching the CLI formatter.
65
66
```typescript { .api }
67
/**
68
* Format the TypeScript diagnostics to human readable output
69
* @param diagnostics - List of TypeScript diagnostics
70
* @param showDiff - Display difference between expected and received types
71
* @returns Formatted diagnostics output
72
*/
73
function formatter(diagnostics: Diagnostic[], showDiff?: boolean): string;
74
```
75
76
**Usage Examples:**
77
78
```typescript
79
import tsd, { formatter } from "tsd";
80
81
const diagnostics = await tsd();
82
83
// Basic formatting
84
if (diagnostics.length > 0) {
85
console.log(formatter(diagnostics));
86
}
87
88
// With type difference display
89
const formattedWithDiff = formatter(diagnostics, true);
90
console.log(formattedWithDiff);
91
92
// Custom error handling
93
if (diagnostics.length > 0) {
94
const hasErrors = diagnostics.some(d => d.severity === "error");
95
const hasWarnings = diagnostics.some(d => d.severity === "warning");
96
97
console.log(`Found ${diagnostics.length} issues:`);
98
console.log(`- Errors: ${diagnostics.filter(d => d.severity === "error").length}`);
99
console.log(`- Warnings: ${diagnostics.filter(d => d.severity === "warning").length}`);
100
console.log("\nDetails:");
101
console.log(formatter(diagnostics, true));
102
103
if (hasErrors) {
104
process.exit(1);
105
}
106
}
107
```
108
109
### Integration with Testing Frameworks
110
111
#### AVA Integration
112
113
```typescript
114
import test from "ava";
115
import tsd from "tsd";
116
117
test("type definitions", async (t) => {
118
const diagnostics = await tsd();
119
120
t.is(diagnostics.length, 0, "No type errors expected");
121
122
// Or check specific diagnostics
123
const errors = diagnostics.filter(d => d.severity === "error");
124
t.is(errors.length, 0, `Found ${errors.length} type errors`);
125
});
126
```
127
128
#### Jest Integration
129
130
```typescript
131
import tsd from "tsd";
132
133
describe("Type Definitions", () => {
134
it("should have no type errors", async () => {
135
const diagnostics = await tsd();
136
const errors = diagnostics.filter(d => d.severity === "error");
137
138
expect(errors).toHaveLength(0);
139
});
140
141
it("should validate specific type file", async () => {
142
const diagnostics = await tsd({
143
typingsFile: "dist/api.d.ts",
144
testFiles: ["tests/api.test-d.ts"]
145
});
146
147
expect(diagnostics.filter(d => d.severity === "error")).toHaveLength(0);
148
});
149
});
150
```
151
152
#### Mocha Integration
153
154
```typescript
155
import { expect } from "chai";
156
import tsd from "tsd";
157
158
describe("Type Definitions", () => {
159
it("should pass all type tests", async () => {
160
const diagnostics = await tsd();
161
const errors = diagnostics.filter(d => d.severity === "error");
162
163
expect(errors).to.have.lengthOf(0);
164
});
165
});
166
```
167
168
### Custom Validation Workflows
169
170
```typescript
171
import tsd, { formatter } from "tsd";
172
import fs from "fs/promises";
173
174
async function validateTypes(projectPath: string): Promise<boolean> {
175
try {
176
const diagnostics = await tsd({
177
cwd: projectPath
178
});
179
180
if (diagnostics.length === 0) {
181
console.log("✅ All type tests passed");
182
return true;
183
}
184
185
const errors = diagnostics.filter(d => d.severity === "error");
186
const warnings = diagnostics.filter(d => d.severity === "warning");
187
188
console.log(`Found ${diagnostics.length} issues:`);
189
console.log(`- ${errors.length} errors`);
190
console.log(`- ${warnings.length} warnings`);
191
192
// Write detailed report to file
193
const report = formatter(diagnostics, true);
194
await fs.writeFile("type-check-report.txt", report);
195
196
// Print summary to console
197
console.log(formatter(diagnostics));
198
199
return errors.length === 0;
200
} catch (error) {
201
console.error("Type checking failed:", error.message);
202
return false;
203
}
204
}
205
206
// Usage
207
const success = await validateTypes("/path/to/project");
208
process.exit(success ? 0 : 1);
209
```
210
211
## Error Handling
212
213
**Common Error Scenarios:**
214
215
TSD uses a custom error class internally but does not export it directly. Errors can be identified by checking the constructor name.
216
217
```typescript
218
import tsd from "tsd";
219
220
try {
221
const diagnostics = await tsd({
222
cwd: "/invalid/path"
223
});
224
} catch (error) {
225
// TsdError is not directly exported but is thrown by the main function
226
if (error && typeof error === 'object' && error.constructor.name === 'TsdError') {
227
// Handle TSD-specific errors
228
console.error("TSD Error:", error.message);
229
230
// Common error messages:
231
// - "No `package.json` file found in `<path>`"
232
// - "The type definition `<file>` does not exist at `<path>`"
233
// - "Could not find any test files with the given pattern(s)"
234
// - "The test file `<file>` does not exist in `<path>`"
235
} else {
236
// Handle other errors
237
console.error("Unexpected error:", error);
238
}
239
}
240
```
241
242
## Configuration Integration
243
244
### Package.json Configuration
245
246
The programmatic API respects package.json configuration:
247
248
```json
249
{
250
"name": "my-package",
251
"tsd": {
252
"directory": "type-tests",
253
"compilerOptions": {
254
"strict": false,
255
"target": "es2020"
256
}
257
}
258
}
259
```
260
261
### TypeScript Configuration
262
263
TSD automatically loads TypeScript configuration from `tsconfig.json`:
264
265
```typescript
266
import tsd from "tsd";
267
268
// This will use project's tsconfig.json automatically
269
const diagnostics = await tsd({
270
cwd: "/path/to/project-with-tsconfig"
271
});
272
```
273
274
## Performance Considerations
275
276
```typescript
277
import tsd from "tsd";
278
279
// For large projects, consider limiting test files
280
const diagnostics = await tsd({
281
testFiles: ["src/**/*.test-d.ts"], // Only test src directory
282
});
283
284
// Or test specific areas incrementally
285
const apiDiagnostics = await tsd({
286
typingsFile: "dist/api.d.ts",
287
testFiles: ["tests/api.test-d.ts"]
288
});
289
290
const utilsDiagnostics = await tsd({
291
typingsFile: "dist/utils.d.ts",
292
testFiles: ["tests/utils.test-d.ts"]
293
});
294
```