11import ts from "typescript" ;
22import { ParserState } from "./ParserState" ;
3- import { parseProperty } from "./parseProperty" ;
3+ import { getDocumentationStringForDict , parseProperty , parsePropertyForDict } from "./parseProperty" ;
44import { getDocumentationStringForType } from "./getDocumentationStringForType" ;
55import { tryToParseInlineType } from "./parseInlineType" ;
66import { isValidPythonIdentifier } from "./isValidPythonIdentifier" ;
@@ -25,18 +25,40 @@ export const parseTypeDefinition = (
2525 state . statements . push ( definition ) ;
2626 } else {
2727 state . imports . add ( "TypedDict" ) ;
28-
29- const properties = type
28+
29+ const allKeysAreValidPythonIdentifiers = type
3030 . getProperties ( )
31- . filter ( ( v ) => isValidPythonIdentifier ( v . getName ( ) ) )
32- . map ( ( v ) => parseProperty ( state , v ) ) ;
31+ . map ( ( v ) => isValidPythonIdentifier ( v . getName ( ) ) )
32+ . reduce ( ( a , b ) => a && b , true ) ;
3333
34- const definition = `class ${ name } (TypedDict):${
35- documentation
36- ? `\n """\n ${ documentation . replaceAll ( "\n" , " \n" ) } \n """`
37- : ""
38- } \n ${ properties . length > 0 ? properties . join ( `\n ` ) : "pass" } `;
34+ if ( allKeysAreValidPythonIdentifiers ) {
35+ const properties = type
36+ . getProperties ( )
37+ . map ( ( v ) => parseProperty ( state , v ) ) ;
38+
39+ const definition = `class ${ name } (TypedDict):${
40+ documentation
41+ ? `\n """\n ${ documentation . replaceAll ( "\n" , " \n" ) } \n """`
42+ : ""
43+ } \n ${ properties . length > 0 ? properties . join ( `\n ` ) : "pass" } `;
44+ state . statements . push ( definition ) ;
45+ } else {
46+ const properties = type
47+ . getProperties ( )
48+ . map ( ( v ) => parsePropertyForDict ( state , v ) ) ;
49+
50+ const propertyDocumentation = type
51+ . getProperties ( )
52+ . map ( ( v ) => getDocumentationStringForDict ( state , v ) )
53+ . filter ( v => v !== undefined )
54+ . join ( "\n" ) ;
55+
56+ const innerDocstring = documentation ?. replaceAll ( "\n" , " \n" ) + ( propertyDocumentation . length > 0 ? "\n## Entries\n" + propertyDocumentation : "" ) ;
57+ const docstring = innerDocstring . length > 0 ? `\n"""\n${ innerDocstring } \n"""` : "" ;
58+ const definition = `${ name } = TypedDict(${ JSON . stringify ( name ) } , {\n ${ properties . join ( ",\n " ) } \n})${ docstring } ` ;
59+
60+ state . statements . push ( definition ) ;
61+ }
3962
40- state . statements . push ( definition ) ;
4163 }
4264} ;
0 commit comments