forked from TheLartians/TypeScript2Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseTypeDefinition.ts
More file actions
42 lines (36 loc) 路 1.34 KB
/
Copy pathparseTypeDefinition.ts
File metadata and controls
42 lines (36 loc) 路 1.34 KB
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
import ts from "typescript";
import { ParserState } from "./ParserState";
import { parseProperty } from "./parseProperty";
import { getDocumentationStringForType } from "./getDocumentationStringForType";
import { tryToParseInlineType } from "./parseInlineType";
import { isValidPythonIdentifier } from "./isValidPythonIdentifier";
export const parseTypeDefinition = (
state: ParserState,
name: string,
type: ts.Type,
) => {
const inlineType = tryToParseInlineType(state, type, true);
const documentation = getDocumentationStringForType(state.typechecker, type);
if (!state.knownTypes.has(type)) {
// we set the currently parsed type here to prevent recursions
state.knownTypes.set(type, name);
}
if (inlineType) {
const definition = `${name} = ${inlineType}${
documentation ? `\n"""\n${documentation}\n"""` : ""
}`;
state.statements.push(definition);
} else {
state.imports.add("TypedDict");
const properties = type
.getProperties()
.filter((v) => isValidPythonIdentifier(v.getName()))
.map((v) => parseProperty(state, v));
const definition = `class ${name}(TypedDict):${
documentation
? `\n """\n ${documentation.replaceAll("\n", " \n")}\n """`
: ""
}\n ${properties.length > 0 ? properties.join(`\n `) : "pass"}`;
state.statements.push(definition);
}
};