gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:18:41 29 4
gpt4 key购买 nike

我有以下 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 上有很多可用的方法用于创建文档注释的对象,但我还没有找到任何关于如何使用它们的示例。
如果它只能以 doc-comment 格式出现,我也会对此示例感兴趣:
/** Some comment on type */
type TestType = {
/** Some comment on property */
str: string
}

最佳答案

根据@AlexWayne 的回答,您似乎可以将每个 Node 包装起来成addSyntheticLeadingComment称呼。然后,您可以指定介于 /* 之间的原始文本。和 */ token 。

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
}
如果你想做 doc-comment 风格的评论,你可以这样做:
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
}
但是你是靠自己的缩进。

关于Typescript AST 工厂 - 如何使用注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67575784/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com