0
# Advanced Parser API
1
2
Direct access to the core Parser class for advanced use cases requiring fine-grained control over component analysis and custom TypeScript program integration.
3
4
## Capabilities
5
6
### Parser Class
7
8
The core parser class that performs TypeScript AST analysis and component documentation extraction.
9
10
```typescript { .api }
11
/**
12
* Core parser class for extracting component documentation
13
* @param program - TypeScript program instance
14
* @param opts - Parser configuration options
15
*/
16
class Parser {
17
constructor(program: ts.Program, opts: ParserOptions);
18
}
19
```
20
21
**Usage Examples:**
22
23
```typescript
24
import { Parser } from "react-docgen-typescript";
25
import * as ts from "typescript";
26
27
// Create TypeScript program
28
const program = ts.createProgram(
29
["./src/Button.tsx"],
30
{
31
jsx: ts.JsxEmit.React,
32
target: ts.ScriptTarget.ES2019
33
}
34
);
35
36
// Create parser instance
37
const parser = new Parser(program, {
38
shouldExtractLiteralValuesFromEnum: true,
39
propFilter: (prop) => !prop.name.startsWith('_')
40
});
41
```
42
43
### Component Information Extraction
44
45
Extract documentation for a specific component symbol.
46
47
```typescript { .api }
48
/**
49
* Extract component documentation from TypeScript symbol
50
* @param exp - TypeScript symbol representing the component
51
* @param source - Source file containing the component
52
* @param componentNameResolver - Optional custom name resolver
53
* @param customComponentTypes - Optional custom component type names
54
* @returns Component documentation or null if not a valid component
55
*/
56
getComponentInfo(
57
exp: ts.Symbol,
58
source: ts.SourceFile,
59
componentNameResolver?: ComponentNameResolver,
60
customComponentTypes?: string[]
61
): ComponentDoc | null;
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
import { Parser } from "react-docgen-typescript";
68
import * as ts from "typescript";
69
70
const parser = new Parser(program, {});
71
const sourceFile = program.getSourceFile("./src/Button.tsx");
72
const checker = program.getTypeChecker();
73
74
if (sourceFile) {
75
const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
76
77
if (moduleSymbol) {
78
const exports = checker.getExportsOfModule(moduleSymbol);
79
80
exports.forEach(exportSymbol => {
81
const componentDoc = parser.getComponentInfo(
82
exportSymbol,
83
sourceFile,
84
// Custom name resolver
85
(exp, source) => {
86
if (exp.getName() === "default") {
87
return "CustomButton";
88
}
89
return undefined;
90
},
91
// Custom component types
92
["MyCustomComponent"]
93
);
94
95
if (componentDoc) {
96
console.log("Found component:", componentDoc.displayName);
97
}
98
});
99
}
100
}
101
```
102
103
### Props Information Extraction
104
105
Extract detailed property information from a props symbol.
106
107
```typescript { .api }
108
/**
109
* Extract props documentation from TypeScript symbol
110
* @param propsObj - TypeScript symbol representing props interface/type
111
* @param defaultProps - Optional default prop values
112
* @returns Props documentation object
113
*/
114
getPropsInfo(
115
propsObj: ts.Symbol,
116
defaultProps?: StringIndexedObject<string>
117
): Props;
118
```
119
120
**Usage Examples:**
121
122
```typescript
123
import { Parser } from "react-docgen-typescript";
124
125
const parser = new Parser(program, {
126
savePropValueAsString: true
127
});
128
129
// Assuming you have a props symbol from component analysis
130
const propsInfo = parser.getPropsInfo(propsSymbol, {
131
variant: "primary",
132
size: "medium"
133
});
134
135
Object.entries(propsInfo).forEach(([propName, propInfo]) => {
136
console.log(`${propName}: ${propInfo.type.name}`);
137
console.log(` Required: ${propInfo.required}`);
138
console.log(` Description: ${propInfo.description}`);
139
if (propInfo.defaultValue) {
140
console.log(` Default: ${propInfo.defaultValue.value}`);
141
}
142
});
143
```
144
145
### Component Type Detection
146
147
Detect and extract props from different component patterns.
148
149
```typescript { .api }
150
/**
151
* Extract props symbol from functional component type
152
* @param type - TypeScript type of the component
153
* @returns Props symbol or null if not a functional component
154
*/
155
extractPropsFromTypeIfStatelessComponent(type: ts.Type): ts.Symbol | null;
156
157
/**
158
* Extract props symbol from class component type
159
* @param type - TypeScript type of the component
160
* @returns Props symbol or null if not a class component
161
*/
162
extractPropsFromTypeIfStatefulComponent(type: ts.Type): ts.Symbol | null;
163
```
164
165
**Usage Examples:**
166
167
```typescript
168
import { Parser } from "react-docgen-typescript";
169
170
const parser = new Parser(program, {});
171
const checker = program.getTypeChecker();
172
173
// For a component symbol
174
const componentType = checker.getTypeOfSymbolAtLocation(
175
componentSymbol,
176
componentSymbol.valueDeclaration!
177
);
178
179
// Try extracting as functional component
180
let propsSymbol = parser.extractPropsFromTypeIfStatelessComponent(componentType);
181
182
if (!propsSymbol) {
183
// Try extracting as class component
184
propsSymbol = parser.extractPropsFromTypeIfStatefulComponent(componentType);
185
}
186
187
if (propsSymbol) {
188
const propsInfo = parser.getPropsInfo(propsSymbol);
189
console.log("Props found:", Object.keys(propsInfo));
190
}
191
```
192
193
## Advanced Use Cases
194
195
### Custom TypeScript Program Integration
196
197
```typescript
198
import { Parser } from "react-docgen-typescript";
199
import * as ts from "typescript";
200
201
// Create program with custom options
202
const compilerOptions: ts.CompilerOptions = {
203
jsx: ts.JsxEmit.ReactJSX,
204
target: ts.ScriptTarget.ES2020,
205
moduleResolution: ts.ModuleResolutionKind.NodeJs,
206
allowSyntheticDefaultImports: true,
207
esModuleInterop: true
208
};
209
210
const filePaths = ["./src/components/*.tsx"];
211
const program = ts.createProgram(filePaths, compilerOptions);
212
213
// Custom parser with advanced options
214
const parser = new Parser(program, {
215
propFilter: (prop, component) => {
216
// Advanced filtering logic
217
return !prop.name.startsWith('data-') &&
218
!prop.parent?.fileName.includes('node_modules');
219
},
220
componentNameResolver: (exp, source) => {
221
// Advanced name resolution
222
const fileName = source.fileName.split('/').pop()?.replace('.tsx', '');
223
if (exp.getName() === 'default' && fileName) {
224
return fileName.charAt(0).toUpperCase() + fileName.slice(1);
225
}
226
return undefined;
227
},
228
shouldExtractLiteralValuesFromEnum: true,
229
shouldExtractValuesFromUnion: true,
230
customComponentTypes: ['StyledComponent', 'MotionComponent']
231
});
232
```
233
234
### Batch Component Analysis
235
236
```typescript
237
import { Parser } from "react-docgen-typescript";
238
239
const parser = new Parser(program, parserOptions);
240
const sourceFiles = program.getSourceFiles()
241
.filter(sf => sf.fileName.includes('/components/'));
242
243
const allComponentDocs: ComponentDoc[] = [];
244
245
sourceFiles.forEach(sourceFile => {
246
const checker = program.getTypeChecker();
247
const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
248
249
if (moduleSymbol) {
250
const exports = checker.getExportsOfModule(moduleSymbol);
251
252
exports.forEach(exportSymbol => {
253
const componentDoc = parser.getComponentInfo(exportSymbol, sourceFile);
254
if (componentDoc) {
255
allComponentDocs.push(componentDoc);
256
}
257
});
258
}
259
});
260
261
console.log(`Found ${allComponentDocs.length} components`);
262
```
263
264
## Type Definitions
265
266
```typescript { .api }
267
interface StringIndexedObject<T> {
268
[key: string]: T;
269
}
270
271
type ComponentNameResolver = (
272
exp: ts.Symbol,
273
source: ts.SourceFile
274
) => string | undefined | null | false;
275
```
276
277
## Error Handling
278
279
The Parser class methods can encounter various error conditions:
280
281
- **Invalid TypeScript Program**: Constructor fails if program has compilation errors
282
- **Malformed Component**: `getComponentInfo` returns null for invalid components
283
- **Missing Props Interface**: `getPropsInfo` returns empty object for components without props
284
- **Type Resolution Errors**: Methods handle unresolvable types gracefully
285
286
```typescript
287
import { Parser } from "react-docgen-typescript";
288
289
try {
290
const parser = new Parser(program, options);
291
const componentDoc = parser.getComponentInfo(symbol, sourceFile);
292
293
if (componentDoc === null) {
294
console.log("Symbol is not a valid React component");
295
}
296
} catch (error) {
297
console.error("Parser creation failed:", error.message);
298
}
299
```