/
convert-expression.ts
64 lines (57 loc) · 1.75 KB
/
convert-expression.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import * as ts from "typescript";
/**
* Return the default value of the given node.
*
* @param node The TypeScript node whose default value should be extracted.
* @returns The default value as a string.
*/
export function convertDefaultValue(
node: ts.Declaration | undefined
): string | undefined {
const anyNode = node as any;
if (anyNode?.initializer) {
return convertExpression(anyNode.initializer);
} else {
return undefined;
}
}
export function convertExpression(expression: ts.Expression): string {
switch (expression.kind) {
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.TrueKeyword:
case ts.SyntaxKind.FalseKeyword:
case ts.SyntaxKind.NullKeyword:
case ts.SyntaxKind.NumericLiteral:
case ts.SyntaxKind.PrefixUnaryExpression:
case ts.SyntaxKind.Identifier:
return expression.getText();
}
if (
ts.isArrayLiteralExpression(expression) &&
expression.elements.length === 0
) {
return "[]";
}
if (
ts.isObjectLiteralExpression(expression) &&
expression.properties.length === 0
) {
return "{}";
}
// a.b.c.d
if (ts.isPropertyAccessExpression(expression)) {
const parts = [expression.name.getText()];
let iter = expression.expression;
while (ts.isPropertyAccessExpression(iter)) {
parts.unshift(iter.name.getText());
iter = iter.expression;
}
if (ts.isIdentifier(iter)) {
parts.unshift(iter.text);
return parts.join(".");
}
}
// More complex expressions are generally not useful in the documentation.
// Show that there was a value, but not specifics.
return "...";
}