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

时间:2017-04-23 16:30:37

标签: angular typescript underscore.js

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

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

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

如何抑制此类错误?

2 个答案:

答案 0 :(得分:2)

由于您使用的是Angular,我假设您使用的是模块

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

在Saravana的回答中,您应该首先安装@ types / underscore包。

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

npm uninstall --save @types/lodash

npm install --save @types/underscore

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

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

ES Module< => CommonJS互操作风格(首选)

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

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

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

TypeScript CommonJS as NameSpace Interop风格(非标准)

import * as _ from 'underscore';

TypeScript CommonJS样式(也适用于AMD / UMD)

import _ = require('underscore');

答案 1 :(得分:1)

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