Typescript Fundamentals

What is Typescript?

Maintaining 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
  • TypeScript is a free and open source programming language developed and maintained by Microsoft.

  • It is a superset of JavaScript. So you can write javascript code in typescript.

    Today’s browsers support ES 5 (Ecma script 5, which is the current standard of writing javascript).
    standard
  • Enables static typing and class-based object-oriented programming to javascript.

  • Another key feature is that Angular 2 is written in typescript.
    (Ref – Wikipedia)

Supported Editors We can write typescript using any one of the below editors.

  • VisualStudio.
  • Node.js
  • SublimeEditor
  • TypeScript play ground

How typescript works

Typescript compiler converts code written in typescript to javascript,

code  code  code

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 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.

Web Application

Add an HTML page in the solution.

HTML page

Add a typescript file in the project and name it typescriptDemo.ts (*.ts is the extension of typescript files).

Add

Open “typescriptDemo.ts” in visual studio, and create a Movie class, with a constructor which takes movie “name” as parameter and have a function “Play()”.

code

In this code you can see that we have specified that 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.

code

Now save this typescriptDemo.ts file and it will generate javascript file with the same name as typescriptDemo.js. You have to manually include this file in to the project because “TSC” compiler generates *.js file when you save *.ts file.

Below is the javascript code generated by “TSC” compiler.

code
Add “typescriptDemo.js” in 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.

Up Next
    Ebook Download
    View all
    Test
    Read by 16 people
    Download Now!
    Learn
    View all