admin管理员组

文章数量:1390482

Context

In a JavaScript file, let require be a variable (whether top-level or local, in a function, etc.), that does not work like the CommonJS one:

function () {
    ...

    /**
     * @param {string} s
     * @returns {number}
     */
    function require(name) { ... }

    const someNumber = require('someName');

    ...
}

Playground demo

Issue

If I use it (as above), TypeScript assumes someNumber is an import and raises a type import error:

Cannot find module 'someName' or its corresponding type declarations.

From my understanding this is because TypeScript assumes any variable named require is the CommonJS import object.

Is there some way to make a variable named require work as any other variable?

Additional details

I could not find a way to disable this behavior in the tsconfig.json file.

I can specify the output type:

/** @type {number} */
const someNumber = require('someName');

but ideally I would not want to change the code on use site of require, only where it is declared.

本文标签: commonjsMake quotrequirequot work like any function with TypeScript type inferenceStack Overflow