Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 556
TechCrunch Avatar asked Apr 01 '17 23:04

TechCrunch


1 Answers

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.

like image 144
pixelbits Avatar answered Oct 14 '22 02:10

pixelbits