.NET & Funky Fresh

Syndication

News

  • <script type="text/javascript" src="http://ws.amazon.com/widgets/q?ServiceVersion=20070822&amp;MarketPlace=US&amp;ID=V20070822/US/bluspiconinc-20/8001/8b68bf4b-6724-40e7-99a5-a6decf6d8648"> </script>
Introducing TypeScript

This is the first tech coming out of Microsoft in several years that I’m excited about….really excited about. So, I thought I would take you, dear reader, on a learning adventure with me. Let’s dive in…

What is TypeScript?

TypeScript is a new programming language that Microsoft has been working on, apparently, for several years now. Anders Hejlsberg, creator of C#, has recently been involved with a small team of talented language gurus to bring it to us in the initial pre-release form.

Simply stated: TypeScript is a superset of the JavaScript programming language which can be compiled to plain Javascript. The superset distinction is important here. Every Javascript program is a TypeScript program and will compile with the TypeScript compiler without any alterations necessary. TypeScript works with any existing JavaScript libraries without the need for any sort of interoperability dance.

Why Use TypeScript?

TypeScript brings several of the features of ECMAScript 6th Edition to ECMAScript 3rd Edition compatible browsers and runtimes. This means you can have several of the cool features of tomorrow’s Javascript…today. Some of the most notable features are classes, modules and lexically scoped this (via arrow functions). So, by learning TypeScript today, you are also going to be learning some ECMAScript 6th Edition…that’s a pretty good return on your investment even if TypeScript is a complete flop….which I doubt it will be.

In addition to getting vNext JS features available in present and older browsers, TypeScript adds a structural type system and strong type inference to JavaScript. This opens the door to declared API contracts, better intellisense, refactoring and it naturally transforms many runtime errors into code squiggles or compile errors. As someone who spends 60+ hours a week now writing JS code…much of which is on a very large-scale SPA…I can tell you this is a big deal in terms of maintainability.

How Do I Get It?

Microsoft has two key locations on the web you need to know. The first is http://www.typescriptlang.org/ From there you can download the language specification, watch a Channel 9 Video with Anders introducing the language, play with the language directly from your browser and run some samples. You’ll also find download links for the VS2012 plugin and compiler tools as well as the source. WAIT. Did I just say source? YES. TypeScript is completely open source on CodePlex under the Apache License 2.0.  You can git clone that sucka to your heart’s content…which brings me to the second web location you need to know: http://typescript.codeplex.com/

How Do I Get Involved?

As I mentioned, TypeScript is on CodePlex. There’s a community building up there already. So you can jump into the discussion forums to ask questions…or answer them with your new found knowledge :)  Naturally, you can submit bugs and feature requests too. There’s also a fair amount of info accumulating on stack overflow now.

Show Me How to Write a Program!!!

  1. Download the tooling and run the msi or install it as a node package with: npm install –g typescript
  2. Once this is done, you’ve got a new exe added to your command path called “tsc” You guessed it. That stands for “TypeScript Compiler.”
  3. To compile a program it’s as simple as typing this on the command prompt: tsc myCode.ts
  4. .ts is the extension for TypeScript source files.
  5. .d.ts is the extension for TypeScript declaration source files (more on that in a future post)

Let’s do it! Create a new file and call it…dum dum dum….helloworld.ts. You can open it in any text editor, but if you’ve installed the VS tools above, you should open it in VS…it’s got bling.

Now, let’s write some code. This will be a pretty bloated hello world example, but it will show you some fun language stuff in the process. Here’s the code to put in the helloworld.ts file:

module HelloWorld {
    class Messenger {
        repeat: number;

        constructor (public message = "Hello World") {
            this.repeat = 1;
        }

        speak() {
            for (var i = 0; i < this.repeat; i++) {
                console.log(this.message);
            }
        }

        static SayHelloInSlang() { 
            new Messenger("'Sup World?").speak();
        }
    }

    var m = new Messenger();
    m.speak();

    Messenger.SayHelloInSlang();
}

To get the full VS experience,  you should type this in manually, rather than copy/paste. The reason for that is that VS will show you errors, types, etc. as you type the code. You’ll also get intellisense. Here’s a few things to notice about this code:

  1. It’s modularized! This is called an internal module. You can also create external modules which the compiler can transform into CommonJS modules or AMD modules (yes you can use it with require.js :) whoohoo). You can tell the compiler how to transform your external modules via the –module switch. This enables you to have a single source set of modules that could run on the server in Node with CommonJS and in the browser with AMD using require.js. Nice. The –module switch defaults to CommonJS, but you can provide the value of amd to build for require.js or a similar amd module loader. But, that’s not related to this code…just a bonus tidbit. This is an internal module which means it will compile to a standard immediately executed function closure-based module.
  2. There is a class!!! The compiler will help you call that ctor with new…no more forgotten new keywords on ctor functions. But you can also more succinctly create classes than with the standard prototype-based syntax you normally need.
  3. The ctor has a default parameter value. Also, the public modifier instructs the compiler that the parameter’s value should automatically be stored into a public property of the object. Nice and succinct.
  4. There’s a static function on the class.
  5. Mouse over things and you will see that there’s some nice type inference happening on variables and function signatures…even though only one type is declared anywhere.
  6. Intellisense is beautiful.
  7. Try refactoring something. It works :)

Now, let’s compile the code. Open your command prompt and navigate to the folder you placed helloworld.ts in. Type the following:

tsc helloworld.ts

The compiler outputs a .js file with the following JavaScript code:

var HelloWorld;
(function (HelloWorld) {
    var Messenger = (function () {
        function Messenger(message) {
            if (typeof message === "undefined") { message = "Hello World"; }
            this.message = message;
            this.repeat = 1;
        }
        Messenger.prototype.speak = function () {
            for(var i = 0; i < this.repeat; i++) {
                console.log(this.message);
            }
        };
        Messenger.SayHelloInSlang = function SayHelloInSlang() {
            new Messenger("'Sup World?").speak();
        }
        return Messenger;
    })();    
    var m = new Messenger();
    m.speak();
    Messenger.SayHelloInSlang();
})(HelloWorld || (HelloWorld = {}));

As you can see, it’s just standard JavaScript code. There is no runtime component to TypeScript. Everything boils down to plain JavaScript.

Of course there’s lots more to TypeScript. We’ve barely scratched the surface. I’m planning to write some more blog posts covering my escapades. Hopefully we can talk more about external modules, structural types, interfaces, lambdas, etc. See ya next time!


Posted 10-02-2012 11:46 AM by Rob Eisenberg

[Advertisement]

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)