TechCrunch
TechCrunch

Reputation: 3134

How to use types/select2 in a Angular 2 project?

I am developing Angular 2 project with Typescript. I want to be able to use select2 and I don't see any stable feature rich plugins equivalent to select2. However I came across types/select2 in DefinitelyTyped project. I'm not sure how to use them in my project. I can't find examples of other DefinitelyTyped libraries also. I'm new to both TS and Angular 2. Can someone provide pointers on how I should used this ?

I understand I can include the library using my package.json but no idea how I can use in a component.

Upvotes: 5

Views: 6591

Answers (3)

Mariel Quezada
Mariel Quezada

Reputation: 101

I solve this by

import { Select2 } from 'select2'

and also install:

npm install @types/[email protected]

Now i have to run test but no more errors on Typescript slint

Upvotes: 0

alcfeoh
alcfeoh

Reputation: 2267

I had a similar issue and fixed it by importing:

import 'select2';

which I had installed earlier:

npm install select2 --save

Once you've done that, you can use the library through jquery as usual.

Upvotes: 2

Michael Kang
Michael Kang

Reputation: 52867

With @types/select2 installed, it allows the typescript compiler to do static type checking to ensure the Select2 library is being called correctly. It does not change the way you use the select2 - you still need to install the Select2 library and use it as you would have without type checking.

For external dependencies (like jQuery or Select2) you should install their corresponding type definition files, so that the typescript compiler can resolve the external types at compile-time. This is preferred over declaring an any types (i.e. declare var $: any)

Make sure you install jQuery types as well :

npm install @types/jquery

This will install the type definitions under node_modules/@types/jQuery. By default, the typescript compiler will resolve types from the node_modules/@types folder.

For TypeScript NodeJS packages, you can generate type definition files as part of the compilation step and specify index.d.ts in the typings property of your package.json file. In this case, you don't necessarily need to export the type definitions to node_modules/@types.

Upvotes: 4

Related Questions