28

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?

derekbaker783
  • 8,109
  • 4
  • 36
  • 50

2 Answers2

86

Cause

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 assert function from an arrowFunction to standard function.

david_p
  • 5,722
  • 1
  • 32
  • 26
  • 13
    Exactly my problem. Thank you! – Xunnamius Jun 30 '22 at 15:25
  • 1
    It might be more accurate to say that arrow functions can be written in a way that is incompatible with type assertions. So long as you provide explicit type annotation, arrow functions will work just fine ([example](https://github.com/microsoft/TypeScript/issues/34523#issuecomment-700491122)). – Avi Nerenberg Aug 09 '23 at 20:55
3

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");
mPrinC
  • 9,147
  • 2
  • 32
  • 31