Search code examples
typescript

How to overwrite incorrect TypeScript type definition installed via @types/package


Say that I want to use dotenv module in my TypeScript project and install its .d.ts using npm install @types/dotenv --save. Then I realize that the types are not correct. For example, the config() function doesn't return boolean but a richer object.

How do I deal with this situation? Should I just copy the downloaded type definition to another file, update it manually and uninstall @types/dotenv? Is there a better way? (I need the fix right away, not after it has been merged by upstream maintainers.)


Solution

  • I would check that the version of dotenv and the version of @types/dotenv are aligned, that may be the cause of the function missing.

    If they are, then the cleaner way would be to modify the .d.ts yourself.

    In order to do this: npm remove @types/dotenv. Create a folder types on your project. Copy the whole folder dotenv found in node_modules/@types into it.

    Then fix your d.ts in it and modify your tsconfig.json to tell it to also look in your new folder for missing types with typeRoots like this:

    {
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "typeRoots": [
            "./node_modules/@types",
            "./types/",
        ]
    },
    "files": ["./app.ts"]
    }
    

    (Don't forget to add ./node_modules/@types or other types you got with npm that won't be found anymore.)