node.js - 当找不到声明文件时如何使用模块
我有一个使用 node.js 的 TypeScript 项目。我想使用一个 npm 包 country-code-lookup 模块。
问题是它没有支持的类型声明。不过,我仍然想使用它。
我还能在没有类型定义的情况下使用这个包吗?
import * as CountryCodeLookup from "country-code-lookup";
const countryCodes = CountryCodeLookup.countries;
console.log(countryCodes);
当 TypeScript 尝试编译时,我收到以下错误。
TS7016:找不到模块 'country-code-lookup' 的声明文件。'/Users/kay/portal/node_modules/country-code-lookup/index.js' 隐式具有 'any' 类型。尝试执行
npm install @types/country-code-lookup(如果存在)或添加一个新的声明 (.d.ts) 文件,其中包含declare module 'country-code-lookup';
答案#1
如果你能够完全忽略这个库的所有类型检查功能,你有两个选择:
- 在所有导入语句上方添加
// @ts-ignore,如下所示:
// @ts-ignore
import * as CountryCodeLookup from "country-code-lookup";
- 创建一个
any类型的声明文件,这样所有导入都会自动被视为any类型。
为此,请创建一个文件 src/types/country-code-lookup/index.d.ts 并添加以下声明:
// country-code-lookup/index.d.ts
declare module 'country-code-lookup';
在此文件中,以后你可以添加你自己的类型定义。如果它们足够好,将它们推送到 DefinitelyTyped,这样整个社区都可以使用并改进它!
