如何在打字稿中引用下划线而不是 lodash

How to reference underscore and not lodash in typescript

我有一个显然使用 lodash 的 angular2 应用程序。但我在父项目中也有 underscore.js 带下划线字符串。

现在打字稿编译器抱怨 lodash 缺少方法。 但我指的不是 lodash,因为该方法在下划线中。

Property 'classify' does not exist on type 'LoDashStatic'

如何抑制此类错误?

您可以安装 @types/underscore 然后只导入您要使用的方法,它不会抛出任何错误。不要忘记在 tsconfig.json 文件

中添加类型

因为您正在使用 Angular 我假设您正在使用模块

由于您使用的是模块,因此您有一个加载程序或一个处理它们的打包程序,您应该相应地使用下划线。

正如 Saravana 的回答,您应该从安装 @types/underscore 包开始。

此外,如果你不使用 lodash 类型,你应该卸载它们

npm uninstall --save @types/lodash

npm install --save @types/underscore

但是,直接从 @types 包中导入是不正确的用法,而使用下划线作为全局表示无法利用模块。

以下是安装类型包后应如何引用下划线的示例。

ES 模块 <=> CommonJS 互操作样式(首选)

import _ from 'underscore'; // note the absence of @types from the path

如果 TypeScript 为此引发错误但它在运行时有效,请在 tsconfig.json 文件中设置 "allowSyntheticDefaultImports": true

如果这在运行时失败,请尝试其他方法之一。

TypeScript CommonJS 作为命名空间互操作样式(非标准)

import * as _ from 'underscore';

TypeScript CommonJS 风格(也适用于 AMD/UMD)

import _ = require('underscore');