Maintaining a huge code in JavaScript is extremely difficult.
In today’s scenario, we write a lot of JavaScript code for a better UI experience and use JS frameworks like Angular, Backbone, and Knockout. Writing client-side code in typescript can significantly reduce the maintenance cost of your project and helps a C# developer to write javascript code.
Key features of Typescript
How typescript works
Typescript compiler converts code written in typescript to javascript,
Understand the code
I am using VS 2013 editor for this sample code. Any Visual Studio version 2013 (with update 2) and above comes with a built-in Typescript compiler. Install “WebEssentials” for additional support of typescript in visual studio.
Open Visual Studio 2013, create a new project, select ASP.NET Empty Web Application.
Add an HTML page in the solution.
Add a typescript file in the project and name it typescriptDemo.ts (*.ts is the extension of typescript files).
Open “typescriptDemo.ts” in visual studio, and create a Movie class, with a constructor that takes the movie “name” as a parameter and have a function “Play()”.
In this code, you can see that we have specified that the movie name should be of type string and its constructor expects a string type input. This is another benefit of using Typescript, it supports compile-time type safety. Now if you try to pass a number in the object of “Movie” class then you will get below warning immediately.
Now save this typescriptDemo.ts file and it will generate a javascript file with the same name as typescriptDemo.js. You have to manually include this file into the project because the “TSC” compiler generates *.js file when you save *.ts file.
Below is the javascript code generated by the “TSC” compiler.
Add “typescriptDemo.js” in the Index.html page and browse it. You will see an alert message coming on page load. Now enjoy writing javascript with OOP’s features.
Explore more with Typescript’s
official site.
Try
Playground.