-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4_typescript_ast.js
executable file
·62 lines (54 loc) · 1.65 KB
/
4_typescript_ast.js
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
#!/usr/bin/env -S node --no-warnings
import path from "path";
import { fileURLToPath } from "url";
import ts from "typescript";
import data from "../data/input.json" assert { type: "json" };
main();
function main() {
const interfaces = data.map(({ name, type }) =>
ts.factory.createInterfaceDeclaration(
undefined,
`SomeInterface${name}`,
undefined,
undefined,
[
ts.factory.createPropertySignature(
undefined,
"discriminator",
undefined,
ts.factory.createStringLiteral(name),
),
ts.factory.createPropertySignature(
undefined,
"type",
undefined,
ts.factory.createIdentifier(type),
),
],
),
);
const union = ts.factory.createTypeAliasDeclaration(
[ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],
"SomeInterface",
undefined,
ts.factory.createUnionTypeNode(interfaces.map((val) => val.name)),
);
const statements = [...interfaces, union]
.flatMap((val) => [ts.factory.createIdentifier("\n"), val])
.slice(1);
const sourceFile = ts.factory.createSourceFile(
statements,
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
ts.NodeFlags.None,
);
const printerOptions = {
newLine: ts.NewLineKind.LineFeed,
};
const printer = ts.createPrinter(printerOptions);
const result = printer.printFile(sourceFile);
const scriptFile = fileURLToPath(import.meta.url);
const projectDir = path.join(scriptFile, "..", "..");
const scriptFileRel = path.relative(projectDir, scriptFile);
console.log(`/* autogenerated by ${scriptFileRel} */`);
console.log(result);
}