Getting StartedMicrosoft has made it really easy to get started with TypeScript. You have an online web-based code editor cum compiler. They also have a Visual Studio 2012 plugin that works on the Professional and above editions. Since a lot has been made about the benefits of ‘tooling’ while introducing TypeScript, we will download and install the TypeScript plugin.
Note: TypeScript is available in Sublime Text, Vi, Emacs editor
Once the Plugin is installed, start Visual Studio, find the Html Application with TypeScript. Strangely enough it goes under the Visual C# category hence it took a minute to find.
The default application looks as follows
The app.ts file is the Typescript file and the app.js is the compiled output file. Fact is app.js is compiled from TypeScript on each compile. If you run the app as is, it will open up a browser and show a page with a ticking timer
Digging a little
With the default app running now let’s look at the TS code and JS code it compiles to, side-by-side
Amazingly for this little snippet, the number of lines of TS code and the number of JS code is identical!
Now let’s try to understand the TS code a little.
- As C# or VB.NET developers, we are familiar with the class keyword. So we are creating a class called Greeter to start off with.
- Next we are declaring three variables, element, span and timerToken. Here the type definition is a little different from C# as in the Type is annotated after the variable name separated by a colon(:) instead of the C# style [typeName] [variableName] (e.g. String myName;).
- So the variable element is of type HTMLElement
- The variable span is of type HTMLElement
- The variable timerToken is of type number
Here the most significant thing is if you try to assign a string to the timerToken, you immediately get type mismatch feedback as seen below:
- Next we have ‘Lambda’ expressions for anonymous functions. A little superfluous but they the C# geek inside me loves it.
Other goodies include support for ‘namespaces’ using the module keyword. The below example is from the ‘Modules’ walkthrough on http://www.typescriptlang.org/Playground/.
InheritanceAs of now, simple Inheritance is supported in TypeScript. The following example again shows the sample from the TypeScript site.
Signing OffThe one thing I didn’t find yet was typecasting. For example I can’t typecast a Button retrieved using
document.getElementById(…) from a HTMLElement into a HTMLButtonElement.
As a budding language, I am sure the constructs will appear.
In the coming days, we will work more on TypeScript and develop a more complete application using TypeScript to understand it better.
That was a very quick a brief introduction to TypeScript. Microsoft’s newest language. Did it get you excited?
Download the source code here (click on Zip to download as .zip)