最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

commonjs - Make "require" work like any function with TypeScript type inference - Stack Overflow

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论