Reputation: 13807
I have the following ast:
import { factory as f } from 'typescript'
const typeDeclaration = f.createTypeAliasDeclaration(
[],
[],
'TestType',
[],
f.createTypeLiteralNode([
f.createPropertySignature([], 'str', undefined, f.createKeywordTypeNode(SyntaxKind.StringKeyword)),
]),
)
Which represents:
type TestType = {
str: string
}
How would I build an AST representing this code? Are comments even part of the AST?
/* Some comment on type */
type TestType = {
/* Some comment on property */
str: string
}
I have seen there are many methods available on the factory
object for creating doc-comments, but I haven't found any examples on how to use them.
In case it's only possible in doc-comment format I'd be interested in examples for that too:
/** Some comment on type */
type TestType = {
/** Some comment on property */
str: string
}
Upvotes: 4
Views: 1030
Reputation: 13807
Based on @AlexWayne's answer it seems you can wrap each Node
into an addSyntheticLeadingComment
call. You can then specify the raw text that goes between the /*
and */
tokens.
const typeDeclWithComment = addSyntheticLeadingComment(
typeDeclaration, // The node
SyntaxKind.MultiLineCommentTrivia, // Node type
'my comment', // the comment text between comment tokens
true, // add a trailing newline after */
)
Which will result in something like this:
/*my comment*/
type TestType = {
str: string
}
In case you want to do doc-comment style comments, you can do something like:
const typeDeclWithComment = addSyntheticLeadingComment(
typeDeclaration,
SyntaxKind.MultiLineCommentTrivia,
'*\n * First line of doc-comment\n * second line of doc-comment\n ',
true,
)
Which will be printed as:
/**
* First line of doc-comment
* second line of doc-comment
*/
type TestType = {
str: string
}
But you are on your own with indentation.
Upvotes: 4