为什么 ts.getJSDocTags 不返回任何项目?

问题描述 投票:0回答:1

这是我的代码:

const filename = 'example.ts';
const code = `

/** 
 * @description foobar
 * 
 * @see test
 */
class Foo  {};
`;

const sourceFile = ts.createSourceFile(filename, code, ts.ScriptTarget.ESNext);

const visitNode = (node: ts.Node) => {
  ts.forEachChild(node, visitNode);
  console.log(ts.SyntaxKind[node.kind], node);
  console.log('--', ts.getJSDocTags(node));
  console.log(
    ts.forEachLeadingCommentRange(
      sourceFile.text,
      node.getFullStart(),
      (pos, end, kind) => {
        console.log(sourceFile.text.slice(pos, end));
      }
    )
  );
};

ts.forEachChild(sourceFile, visitNode);

我不明白为什么对

ts.getJSDocTags
的任何调用都会返回项目。

这是一个 stackblitz 重现

typescript
1个回答
0
投票

我已经调试了您的示例代码(stackblitz repro。)并发现了由于

empty array
而返回
ts.getJSDocTags(node)
的问题。

请检查打字稿库:

node_modules/typescript/lib/tsc.js

有问题。

首先检查函数

getJSDocTags
,我们正在调用
getJSDocTagsWorker
函数,
noCache
参数值为
false

function getJSDocTags(node) {
  return getJSDocTagsWorker(
    node,
    /*noCache*/
    false
  );
}

然后检查功能

getJSDocTagsWorker

function getJSDocTagsWorker(node, noCache) {
  var _a;
  if (!canHaveJSDoc(node))
    return emptyArray;
  let tags = (_a = node.jsDoc) == null ? void 0 : _a.jsDocCache;
  if (tags === void 0 || noCache) {
    ... ... ... 
  }
  return tags;
}

这里,

tags
值为
empty array ([])
。因为,
_a.jsDocCache = node.jsDoc.jsDocCache = []
。 另外,
noCache
值为
false

因此,它不会进入第二个 if 块 (

tags === void 0 || noCache
) 并将
tags
值返回为
empty array

附上屏幕短路供参考。

希望对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.