如何将 TypeScript 文件的对象文字 AST 转换为实际代码?

Posted

技术标签:

【中文标题】如何将 TypeScript 文件的对象文字 AST 转换为实际代码?【英文标题】:How to covert object literal AST of TypeScript file to Actual Code? 【发布时间】:2018-08-30 14:58:49 【问题描述】:

我需要将 JSON 或 Object Literal 文件转换为实际代码。怎么做?

const astInJson = "pos":0,"end":79,"flags":0,"kind":268,"text":"export interface Order \n\torderId: string;\n\titineraries(id: string): string;\n\n","bindDiagnostics":[],"languageVersion":5,"fileName":"/Users/myth/Desktop/test-interface.ts","languageVariant":0,"isDeclarationFile":false,"scriptKind":3,"referencedFiles":[],"typeReferenceDirectives":[],"amdDependencies":[],"statements":["pos":0,"end":78,"flags":0,"kind":230,"modifiers":["pos":0,"end":6,"flags":0,"kind":84],"name":"pos":16,"end":22,"flags":0,"escapedText":"Order","members":["pos":24,"end":42,"flags":0,"kind":148,"name":"pos":24,"end":33,"flags":0,"escapedText":"orderId","type":"pos":34,"end":41,"flags":0,"kind":136,"pos":42,"end":76,"flags":0,"kind":150,"name":"pos":42,"end":55,"flags":0,"escapedText":"itineraries","parameters":["pos":56,"end":66,"flags":0,"kind":146,"name":"pos":56,"end":58,"flags":0,"escapedText":"id","type":"pos":59,"end":66,"flags":0,"kind":136],"type":"pos":68,"end":75,"flags":0,"kind":136],"modifierFlagsCache":536870913],"endOfFileToken":"pos":78,"end":79,"flags":0,"kind":1,"externalModuleIndicator":"pos":0,"end":78,"flags":0,"kind":230,"modifiers":["pos":0,"end":6,"flags":0,"kind":84],"name":"pos":16,"end":22,"flags":0,"escapedText":"Order","members":["pos":24,"end":42,"flags":0,"kind":148,"name":"pos":24,"end":33,"flags":0,"escapedText":"orderId","type":"pos":34,"end":41,"flags":0,"kind":136,"pos":42,"end":76,"flags":0,"kind":150,"name":"pos":42,"end":55,"flags":0,"escapedText":"itineraries","parameters":["pos":56,"end":66,"flags":0,"kind":146,"name":"pos":56,"end":58,"flags":0,"escapedText":"id","type":"pos":59,"end":66,"flags":0,"kind":136],"type":"pos":68,"end":75,"flags":0,"kind":136],"modifierFlagsCache":536870913,"nodeCount":15,"identifierCount":5,"identifiers":,"parseDiagnostics":[]

【问题讨论】:

至少在这种情况下,看起来最外面的text属性有源代码。您想要源代码还是要将代码作为模块对象加载到当前 javascript 运行时中? @MattMcCutchen 是的,在文本属性中它存在。但我不想用那个。我想更改对象文字中的一些属性,它应该给我数据作为 Typescript 源代码。简而言之,我需要 JSON 到 Typescript。 【参考方案1】:

如果你有一个ts.SourceFile 对象,你可以使用:

ts.createPrinter().printFile(file)

返回一个字符串。 ts.SourceFile 是一个包含循环引用的数据结构;如果您有一些字段子集作为 JSON,我不知道是否有任何合理的方法可以将其转换回 ts.SourceFile。更多想法可以关注the API to modify and print ASTs that is used by TypeScript's own code fixes。

【讨论】:

以上是关于如何将 TypeScript 文件的对象文字 AST 转换为实际代码?的主要内容,如果未能解决你的问题,请参考以下文章

TypeScript,啥是对象文字的调用签名以及它们如何与泛型类型一起使用?

如何在 TypeScript 中指定定义为对象文字的箭头函数的类型?

在 TypeScript 中使用类型变量访问对象文字不起作用

具有对象文字和 Typescript 的功能性开关盒

如何使 TypeScript 字符串枚举适用于字符串文字并正确进行类型推断

Typescript 索引属性约束检查适用于原始类型但不适用于对象文字?