Node.js – How to use a module when it could not find a declaration file

node.jsreactjstypescript

I have a typescript project using node.js. There is a module i want to use npm package country-code-lookup.

The problem is it does not have a supporting types declaration for it. However, i'd still like to use it.

Is it possible i could still use this package without the typings.

import * as CountryCodeLookup from "country-code-lookup";

   const countryCodes = CountryCodeLookup.countries;
   console.log(countryCodes);

I get the following error when typescript attempts to compile.

TS7016: Could not find a declaration file for module
'country-code-lookup'.
'/Users/kay/portal/node_modules/country-code-lookup/index.js'
implicitly has an 'any' type.
Try npm install @types/country-code-lookup if it exists or add a new declaration (.d.ts) file containing declare module
'country-code-lookup';

Best Answer

If you have no problems simply ignoring all type-checking features for this library, you have two options:

  1. Add // @ts-ignore above all imports, like so:
// @ts-ignore
import * as CountryCodeLookup from "country-code-lookup";
  1. Create a declaration file with any type, so all imports are automatically considered to be of any type.

To do so, create a file src/types/country-code-lookup/index.d.ts Add the following declaration:

// country-code-lookup/index.d.ts
declare module 'country-code-lookup';

In this file, later you can add your own type definitions. If they are good enough, push them do DefinitelyTyped, so all the community can use and improve it!