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

Comments

Dan Vanderboom wrote re: Introducing TypeScript
on 10-02-2012 12:13 PM

Nice write-up, Rob. TypeScript is really exciting!

While Visual Studio provides great support for TypeScript language services, I found in the source code that they've also implemented these in TypeScript itself (with the rest of the compiler). This opens up some interesting possibilities, such as a browser based IDE with rich language services.

So I started looking for a browser-based IDE that might be extensible enough for me to add TypeScript support. I was delightfully surprised to discover that the Cloud9 IDE (at http://c9.io) went live with TypeScript support this morning. Talk about phenomenal response time for an open source project!

This is important because it means there can be development parity among developers spanning a range of operating systems. A programming environment can be tricky to set up, so doing it in the cloud is a big plus. With TypeScript being open source and based on web standards, reach of tools is an important and powerful issue, unlike previous Microsoft-centric development technologies.

Rob Eisenberg wrote re: Introducing TypeScript
on 10-02-2012 12:49 PM

Wow. That is impressive. I've dabbled with Cloud9 IDE, but didn't think they would be up and running with something like this so fast. I'm going to go check it out....before you know it Microsoft will have an Azure integrated, browser-based TypeScript IDE...

Jayme Edwards wrote re: Introducing TypeScript
on 10-03-2012 7:13 PM

I'm sorry but coffee script reads 100x better and is open source. Shame on MS creating their own version of an already successful technology instead of supporting an already existing one that's supported by the community *again*.

Rob Eisenberg wrote re: Introducing TypeScript
on 10-07-2012 2:16 PM

TypeScript is open source...including all the tooling. We are also talking about two totally different approaches to the problem here. Also, TypeScript addresses a lot of issues that CoffeeScript cannot via its support for structural types and type inference. They are two different approaches to the same problem. What's wrong with having another programming language to choose from?

Ken McGelt wrote re: Introducing TypeScript
on 10-09-2012 11:19 AM

OK, so they figured out how to make it look like they've moved C# 'to the browser', without requiring a plugin and a runtime system on the client machine, kinda sorta, but not really.  :-/

pfffft

I'll stick with my CoffeeScript, thanks.

MichaelD! wrote re: Introducing TypeScript
on 10-10-2012 12:20 PM

... finally.  Now we just need a XamlScript equivalent and coding will be fun again. :P

Evan wrote re: Introducing TypeScript
on 10-19-2012 1:40 PM

Re-write Durandal in TypeScript! right meow!

^_^

KirstenBowen wrote re: Introducing TypeScript
on 10-22-2012 3:07 AM

Should there be another persuasive post you can share next time, I’ll be surely waiting for it.

Evan wrote re: Introducing TypeScript
on 10-24-2012 8:30 PM

Rob, I'm curious to know your opinion on Typescript. I'm not sure if you've been playing with it much since this initial post when Typescript first came out.  But, once you start writing lots of typescript how is the debugging experience? Does it cost more time once you find the bug in JavaScript then you have to find the spot in typescript that it corresponds too?  Does the JS that typescript compiles out too make debugging harder?

Thanks,

Evan

Rob wrote re: Introducing TypeScript
on 11-07-2012 2:11 PM

I played with TypeScript more after this post. I think it has a ton of potential...but right now it's probably more trouble than it's worth. The reason is that the type system isn't quite finished. It's lacking generics which are needed to handle a number of real world scenarios. Also, the thing that's going to make or break this, is whether or not a ton of js libraris have TypeScript definition files available for them. Otherwise, it's a pain in the but to create those yourslelf. In order to stay productive you just end up making things of type any, which takes away the benefits of TypeScript. To summarize again: I think it has a lot of potential, but it's a little bit rough right now and probably not good for real world use.

Evan wrote re: Introducing TypeScript
on 11-19-2012 6:23 PM

I found a project on GitHub which has a lot of typescript definitions for popular libraries.  I'm not sure how complete it is but its a good start.

github.com/.../DefinitelyTyped

Marwijn wrote re: Introducing TypeScript
on 12-04-2012 8:16 AM

Hello Rob,

I've made some effort to put a typescript example to your durandal project. If you wish you can find the code on github.

Marwijn.

codeBelt wrote re: Introducing TypeScript
on 12-22-2012 9:30 PM

Good article! You should check out my <a href="www.codebelt.com/.../">TypeScript Tutorials</a>

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)