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

Viewed 5637

I have the JavaScript code below, and I'm using the TypeScript Compiler (TSC) to provide type-checking as per the 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);
        });
    });
});

I'm seeing this error:

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.

How can I resolve this error?

3 Answers

For anyone seeing this, if you have written your own assert function, keep in mind that TypeScript cannot use arrowFunctions for assertions.

See https://github.com/microsoft/TypeScript/issues/34523

Fix: change your code from arrowFunction to standard function.

You need to add a JSDoc type annotation for your assert variable such as in the example below. You can add a more specific type than {any} if you like.

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

See this Github issue for more info.

Sorry for not going deeper in the topic of the particular assert you use, it seems it is node native, which is different than those supported by TypeScript

But nevertheless, this can be a good hint:

// 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);
    }
};

And this is how you would use it:

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