如何解决“断言要求调用目标中的每个名称都使用显式类型注释.ts(2775)进行声明”?

der*_*783 37 javascript jsdoc typescript tsc

我有下面的 JavaScript 代码,并且我正在使用 TypeScript 编译器 (TSC) 根据Typescript Docs JSDoc Reference提供类型检查。

const assert = require('assert');
const mocha = require('mocha');

mocha.describe('Array', () => {
    mocha.describe('#indexOf()', () => {
        mocha.it('should return -1 when the value is not present', 
        /** */
        () => {
            assert.strictEqual([1, 2, 3].indexOf(4), -1);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

我看到这个错误:

Assertions require every name in the call target to be declared with an explicit type annotation.ts(2775)
SomeFile.test.js(2, 7): 'assert' needs an explicit type annotation.
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个错误?

dav*_*d_p 112

原因

对于看到此内容的任何人,如果您编写了自己的断言函数,请记住 TypeScript 无法使用arrowFunctions进行断言。

请参阅https://github.com/microsoft/TypeScript/issues/34523

使固定

将断言函数从arrowFunction更改为标准函数

  • 正是我的问题。谢谢你! (15认同)
  • 更准确地说,箭头函数可以用与类型断言不兼容的方式编写。只要您提供显式类型注释,箭头函数就可以正常工作([示例](https://github.com/microsoft/TypeScript/issues/34523#issuecomment-700491122))。 (4认同)

mPr*_*inC 6

抱歉,没有深入讨论assert您使用的特定主题,它似乎是 Node Native,这与TypeScript 支持的不同

但尽管如此,这可能是一个很好的提示:

// This is necessary to avoid the error: `Assertions require every name in the call target to be declared with an explicit type annotation.ts(2775)`
// `assertion.ts(16, 14): 'assert' needs an explicit type annotation.`
// https://github.com/microsoft/TypeScript/issues/36931#issuecomment-846131999
type Assert = (condition: unknown, message?: string) => asserts condition;
export const assert: Assert = (condition: unknown, msg?: string): asserts condition => {
    if (!condition) {
        throw new AssertionError(msg);
    }
};
Run Code Online (Sandbox Code Playgroud)

这就是你将如何使用它:

assert(pathStr || pathParts, "Either `pathStr` or `pathParts` should be defined");
Run Code Online (Sandbox Code Playgroud)