How do I override incorrect types from a package that ships its own .d.ts?

1.1k Views Asked by At

I am using chalk with a JavaScript project that I'm checking with TypeScript's checkJs flag.

The JavaScript code imports it like so:

const chalk = require('chalk')

Unfortunately, chalk ships its own types, and its types are wrong. It should use the syntax export = chalk (which is TypeScript's syntax for CommonJS) but instead does export default chalk.

Somebody submitted a PR to fix it, but the project hasn't merged any PRs in a while.

How can I work around the bad export from the chalk typings?

1

There are 1 best solutions below

0
Nathan Shively-Sanders On

You can override the package's types by providing a path mapping:

  1. Create a file named chalk-override.d.ts in your project root. Copy the chalk types in there and fix them.
  2. Add the following to your tsconfig.json (create one with tsc --init --checkJs if you haven't already):

    {
        // ... other settings ...
    
        "baseUrl": "./",
        "paths": {
            "chalk": ["chalk-override"]
        }
    }