Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a module when it could not find a declaration file

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';

like image 491
Kay Avatar asked Jun 20 '19 15:06

Kay


People also ask

Could not find a declaration file for module react JSX runtime?

When you have this error, it is usually because you installed a library and you didn't install the types of that library. To fix this error, you need to install @types/library-name using your package manager (npm or yarn).

What is declare module in TypeScript?

The TypeScript declares module is one of the modules and keyword it is used for to surround and define the classes, interfaces; variables are also declared it will not originate with the TypeScript like that module is the set of files that contains values, classes, functions/methods, keywords, enum all these contains ...


1 Answers

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!

like image 57
Danilo Fuchs Avatar answered Sep 25 '22 16:09

Danilo Fuchs