如何解决'Assertions require every name in the call target to be declared with an explicit type annotation.ts(2775)'?

How to resolve 'Assertions require every name in the call target to be declared with an explicit type annotation.ts(2775)'?

我有下面的 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);
        });
    });
});

我看到这个错误:

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.

我该如何解决这个错误?

您需要为 assert 变量添加 JSDoc 类型注释,如下例所示。如果愿意,您可以添加比 {any} 更具体的类型。

/** @type {any} */
const assert = require('assert');

有关详细信息,请参阅 this Github issue

抱歉没有深入探讨您使用的特定 assert 的主题,它似乎是 node native,与 those supported by 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);
    }
};

这就是您的使用方式:

assert(pathStr || pathParts, "Either `pathStr` or `pathParts` should be defined");