3
votes

I have JS/TS code base in my project. Some file looks like:

import Something from '@some-lib/things/something'; // index.jsx file here

const someFunction = () => {
  // do something with "Something"
};

In VS Code and tsc result i have error:

Could not find a declaration file for module '@some-lib/things/something'.

'/Users/user/Projects/project/node_modules/@some-lib/things/something/index.jsx' implicitly has an 'any' type.

Try npm install ... if it exists or add a new declaration (.d.ts) file containing declare module '@some-lib/things/something';

I tried to add definitions by creatig file src/@types/@some-lib/index.d.ts with this content:

declare module '@some-lib/things/something' {
  const Something: (props: React.SVGProps<SVGSVGElement> & {
    size?: number,
    color?: string,
    inline?: boolean,
    className?: string,
  }) => React.ReactElement;

  export default Icon;
}

But i get this error:

Invalid module name in augmentation.
Module '@some-lib/things/something' resolves to an untyped module at '/Users/user/Projects/project/node_modules/@some-lib/things/something/index.jsx', which cannot be augmented.

Please, help me. How can i declare TypeScript types for JS libraries from npm with subdirectories/submodules ?

2

2 Answers

0
votes

I found solution.

If you want to create d.ts for js/jsx files from npm-modules you import like this:

// this is reference to ./node_modules/@some-lib/things/something/index.js
import Something from '@some-lib/things/something' 

you need to

  1. Add paths to your tsconfig.json:
{
 "compilerOptios": {
    // ...
    "baseUrl": ".", // just require for "paths"
    "paths": {
      "@some-lib/*": ["src/types/some-lib"] // 'src/types' is just for example
    }
  }
}
  1. Create file src/types/@some-lib/things/something.d.ts with content:
declare module '@some-lib/things/something' { // equal to import
  const Something = number; // number just for example

  export = Something;
}

As far as I understand, your d.ts file path in should be the same as the path from node_modules, except that its root starts at src/types/ in example.

I really hope this will help you, good luck!