کارخانه AST تایپاسکریپت - چگونه از کامنتها استفاده کنیم؟


من این 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
}

پاسخ شماره ۱

بر اساس پاسخ @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
}

در صورتی که بخواهید کامنتهایی به سبک 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
}

اما در مورد تورفتگی باید خودتان عمل کنید.