dc10
dc10

Reputation: 2198

How to reference underscore and not lodash in typescript

I have an angular2 app which apparently uses lodash. But I also do have underscore.js with underscore string in the parent project.

Now the typescript compiler complains about missing methods on lodash. But I am not referring to lodash since the method is in underscore.

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

How can I suppress such errors ?

Upvotes: 0

Views: 5260

Answers (2)

Aluan Haddad
Aluan Haddad

Reputation: 31833

Since you are using Angular I assume you are using modules

Since you are using modules, you have either a loader or a packager that handles them and you should consume underscore accordingly.

As in Saravana's answer you should start by installing the @types/underscore package.

Additionally make you should uninstall the lodash types if you are not using them

npm uninstall --save @types/lodash

npm install --save @types/underscore

However, importing directly from an @types package is incorrect usage while using a underscore as a global represents a failure to leverage modules.

Here are examples of how you should reference underscore after having installed the types package.

ES Module <=> CommonJS interop style (preferred)

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

If TypeScript raises errors for this but it works at runtime, set "allowSyntheticDefaultImports": true in your tsconfig.json file.

If this fails at runtime, try one of the other approaches.

TypeScript CommonJS as NameSpace Interop style (non-standard)

import * as _ from 'underscore';

TypeScript CommonJS style (also works with AMD/UMD)

import _ = require('underscore');

Upvotes: 1

Jorawar Singh
Jorawar Singh

Reputation: 7621

You can install @types/underscore and then just import that method you want to use and it will not throw any error. Don't forget to add to types in tsconfig.json file

Upvotes: 1

Related Questions