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

bfhwhh0e  于 2023-01-14  发布在  TypeScript
关注(0)|答案(2)|浏览(131)

我有下面的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.

如何解决此错误?

t9aqgxwy

t9aqgxwy1#

如果您已经编写了自己的assert函数,请记住TypeScript不能将arrowFunctions用于Assert。
参见https://github.com/microsoft/TypeScript/issues/34523
修正:将你的代码从arrowFunction改为标准函数.

wtlkbnrh

wtlkbnrh2#

抱歉,没有深入讨论您使用的特定assert的主题,它似乎是节点本机的,这与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");

相关问题