JQuery is one of the most popular JavaScript libraries which exposes a lot of usable APIs for JavaScript developers. It’s an integration with Typescript that may do wonders for you.
I am taking my previous code sample for the demonstration.
In my previous sample, I displayed a message in the alert box, but in this sample, I will display a message in the UI with the help of JQuery functions.
How to integrate with Typescript
- Open project in Visual Studio.
- Right click “TypescriptDemo” project and go to Nuget package manager.
- Type “definitely” in a search box.
You will see the list of libraries; which have an extension as “*.d.ts” and is called ‘DefinitelyTyped”, which are specific to Typescript projects.
For our sample, we will select “jquery.TypeScript.DefinitelyTyped” and install.
This will add a jQuery version of Typescript with an extension same as of Typescript files.
Drag and drop this “jquery.d.ts” file on the “demo.ts” file. This will add a reference to the JQuery library. Now, you are ready to use all the API’s of jQuery in your Typescript files.
Open “demo.ts” and make changes in “Play” function, as shown below:
You can see that we are able to find all relevant “JQuery” functions in the intellisense.
Below is the complete code of “demo.ts” file.
Note
While adding, click event to the button; I used lambda declaration ( ()=> ) instead of writing “function” and this is awesome.
In index.html file, add a ‘div’, ‘button’ and a ‘textbox’.
Now, browse “index.html” and open console, you will see the error, as shown below:
This is because we have not added “jQuery.js” file in our HTML page.
Let’s add the jQuery from Nuget package manager and add a reference in “index.html”.
Now, it is ready to browse “Index.html” and see the output.
I have added the source code for the reference.