TypeScript AST 工厂 - 如何使用注释?

4
我有以下的AST:
import { factory as f } from 'typescript'

const typeDeclaration = f.createTypeAliasDeclaration(
  [],
  [],
  'TestType',
  [],
  f.createTypeLiteralNode([
    f.createPropertySignature([], 'str', undefined, f.createKeywordTypeNode(SyntaxKind.StringKeyword)),
  ]),
)

这代表:

type TestType = {
  str: string
}

我该如何构建一个表示此代码的AST?注释是否包含在AST中?

/* Some comment on type */
type TestType = {
  /* Some comment on property */
  str: string
}

我看到factory对象提供了许多创建文档注释的方法,但我没有找到如何使用它们的示例。

如果只能采用文档注释格式,我也对其示例感兴趣:

/** Some comment on type */
type TestType = {
  /** Some comment on property */
  str: string
}

为什么要在AST中包含非文档注释?我非常确定它们会被删除,因为它们没有功能目的,而与可以提供智能感知和文档的文档注释不同。 - Alex Wayne
@AlexWayne 我正在生成代码。我想弄清楚注释是否是AST的一部分,如果是,如何使用它们,因为生成的代码应该包含注释。 - Balázs Édes
1
嗯,我有点困惑。注释似乎在AST中不存在,但是TypeScript可以将它们从TS传递到JS。那么如果它们不在AST中,它是如何做到的呢? - Alex Wayne
@AlexWayne,在VSCode中似乎还有智能感知、重构等功能可以用于文档注释,这表明至少文档注释是AST的一部分。可能只是使用起来有些棘手,因此才会有这个问题 :) - Balázs Édes
1
似乎文档注释会附加到它们所记录的节点上。您可以通过单击“设置”并打开该功能,在typescript playground中查看任何代码的AST。那么https://dev59.com/tLXna4cB1Zd3GeqPI1Em是否回答了您的问题?在https://github.com/microsoft/TypeScript/issues/17146的末尾,还有一种创建JSDoc注释的方法。 - Alex Wayne
1个回答

4

根据 @AlexWayne 的回答,似乎可以将每个 Node 包装到一个 addSyntheticLeadingComment 调用中。然后,您可以指定放置在 /**/ 标记之间的原始文本。

const typeDeclWithComment = addSyntheticLeadingComment(
  typeDeclaration, // The node
  SyntaxKind.MultiLineCommentTrivia, // Node type
  'my comment', // the comment text between comment tokens
  true, // add a trailing newline after */
)

这将会导致类似于这样的结果:

/*my comment*/
type TestType = {
  str: string
}

如果您想进行文档注释风格的评论,可以这样做:

const typeDeclWithComment = addSyntheticLeadingComment(
  typeDeclaration,
  SyntaxKind.MultiLineCommentTrivia,
  '*\n * First line of doc-comment\n * second line of doc-comment\n ', 
  true, 
)

将输出:

/**
 * First line of doc-comment
 * second line of doc-comment
 */
type TestType = {
  str: string
}

但是关于缩进,你需要自己处理。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接