The JavaScript blog.


languages ES6 tea

Earl Grey

Posted on .

Earl Grey (GitHub: breuleux/earl-grey, License: MIT, npm: earlgrey) by Olivier Breuleux is a language that compiles to JavaScript. It's aware of ES6 features and actually compiles to ES6. It's built using great libraries like babel. Naturally Earl Grey supports sourcemaps.

The syntax is Python inspired, but modern JavaScript shines through. Look at how generators are handled:

gen fib() =  
   var {a, b} = {0, 1}
   while true:
      yield a
      {a, b} = {b, a + b}

fib() each  
   > 100 ->
   n when n mod 2 == 0 ->
      print n

It also has pattern matching, as in the functional language weak type testing:

match thing:  
   0 ->
      print "The thing is zero"
   < 0 ->
      print "The thing is negative"
   R"hello (.*)"? x ->
      ;; note: R"..." is a regular expression
      print 'The thing is saying hello'

One thing that surprised me about Earl Grey is the inclusion of the async and await keywords:

require: request  
g = promisify(request.get)

async getXKCD(n = "") =  
   response = await g('http://xkcd.com/{n}/info.0.json')

   requests = await all 1..10 each i -> getXKCD(i)
   requests each req -> print req.alt

I saw Earl Grey on Hacker News, and wondered how long Olivier has been working on it. According to GitHub, he started work back in March last year, and older versions were mostly written in Earl Grey with a single JavaScript bootstrap file. Over time more dependencies were added, like opg, and more recently Babel for ES5 compilation.

You can find the lexer, parser, and language implementation in the src folder. It's all written in Earl Grey and demonstrates the language features really well -- take a look at the macro files to see what I mean.

The real question is, do you drink Earl Grey with milk? Some say bergamot doesn't go with milk, others say the tannins in black tea needs milk due to a chemical reaction involving fat. I personally prefer milk in Earl Grey, although I almost always drink coffee black.


libraries languages Microsoft typescript

TypeScript Log, Supplemental

Posted on .

This week on DailyJS every post is about TypeScript! This article is a roundup of interesting TypeScript libraries.

This is the end of TypeScript week on DailyJS. I've been going through my email archives looking for TypeScript-related things that people have sent in. Here is a selection! As always, please share anything TypeScript (or JavaScript) related with me by going to contact.dailyjs.com.


VCL.JS (GitHub: vclteam / VCL.JS, License: Apache 2.0) is a component-based web framework. The built-in components are based on Bootstrap, so the UI code should be quite easy to work with if you've used Bootstrap before.

It has deep Visual Studio integration, so Microsoft developers should be able to get started quickly. It even supports data binding and AMD for client-side code.


I'm intrigued by EndGate, a game framework for HTML5 games written in TypeScript. It has APIs for input, graphics, animations (tweening), and collision detection.

There's a tutorial that explains how to use collisions and tweens. It seems to focus on map-based 2D games, which usually work well in browsers anyway.


One of the big things in C# 5.0 was the async modifier and await operator. These keywords allow C# code to be asynchronous, without callbacks or delegate methods.

The asyncawait module for Node is inspired by this API. You can await asynchronous methods, so you get to use non-blocking APIs with synchronous convenience:

var foo = async (function() {  
    var resultA = await (firstAsyncCall());
    var resultB = await (secondAsyncCallUsing(resultA));
    var resultC = await (thirdAsyncCallUsing(resultB));
    return doSomethingWith(resultC);

This module is based on two great projects: node-fibers and bluebird, but it's written with TypeScript:

TypeScript: asyncawait is written in TypeScript (look in the src folder), and includes a type declaration file. TypeScript makes JavaScript development faster, less error-prone, more scaleable, and generally more pleasant.


languages Microsoft typescript

TypeScript's Compiler

Posted on .

This week on DailyJS every post is about TypeScript! This article is all about TypeScript's compiler.

This week a new TypeScript compiler was announced, along with the move of the project to GitHub.

Our work to date on the new compiler has been very promising. At its current level of completeness, the new compiler is able to compile existing real-world TypeScript code 5x faster than the currently shipping compiler. These results are still early. Once the compiler has reached parity, we'll be able to report out a more complete picture of the performance improvements.

You might be wondering how the TypeScript compiler works. The source can be found at GitHub: Microsoft/TypeScript, and is written in TypeScript. It's structured using features and idioms commonly used in TypeScript, like services and generics.

There's a parser, scanner, and the infrastructure needed to work with command-line options and files. The parser generates nodes that are used by an "emitter" that produces the desired output. You'll see a lot of switch statements matching on enums that relate to language constructs.

Comparison with Other Compilers

The CoffeeScript parser is generated from a Jison file -- so unlike TypeScript it has an additional context free grammar file. There are attempts at writing Jison-based TypeScript compilers, which are interesting to look at. LiveScript is also based on Jison.

ClojureScript's compiler transforms ClojureScript into JavaScript. Originally ClojureScript was written in Clojure, and I'm not sure if it's self-hosted yet. There was a fork that is self-hosted, however.


One issue with JavaScript compilers is the fact you have to recompile files to JavaScript whenever you make a change. Fortunately, tsc has a --watch option, so you can write tsc -w file.ts to watch for changes on file.ts. This can easily be used with a module like nodemon to automatically restart the Node process (if you're using Node) as well.

There are also Grunt and Gulp plugins for TypeScript:


It's interesting that there seems to be three main approaches to transpiling JavaScript:

  • Parser based on a context-free grammar
  • Self-hosted hand-written parser
  • External language

If someone had showed me TypeScript I would have assumed it was written with a CLR-based language, so it's cool that it's self-hosted and able to easily run without Microsoft's development tools.


languages Microsoft typescript

TypeFramework: A TypeScript Web Framework

Posted on .

This week on DailyJS every post is about TypeScript! This post is about TypeFramework, a possibly Rails inspired web framwork aimed at TypeScript developers.

One of the aims of TypeScript is to help you write large applications. In Node, the popular idiom is "small modules" -- programs are composed from small packages with APIs based on patterns found in Node's core modules. That means EventEmitter, streams, callbacks with the error-first signature, and modules that return a single function.

This can work well, but people still seem to struggle to maintain larger web applications. Surely a TypeScript MVC framework offers insights on how to structure larger projects?

TypeFramework (GitHub: zekelevu / typeframework, License: MIT, npm: typeframework) by Zeke Kievel is built on Express. It has controllers, models, views, routing, and configuration. The models are based on the Waterline ORM, and they look like this:

class User extends TF.Model {  
  name: string;
  email: string;
  age?: number;


The chainable API is quite nice:

  .where({ name: 'John' })
  .done((err, users: User[]) => { /* callback */ });

Everything looks very much like a lightweight Rails. It will probably help C# developers who want to write things that run on Node, or Rails developers who are transitioning to Node.

What I'd really like to see is a more MVVM-style framework with interfaces for code contracts, services, and ReactiveUI-style APIs. I'd prefer skinny models so I can avoid putting business logic in them and use my own persistance layer. I think TypeScript is perfectly suited to this, but I haven't yet found such a framework.


languages Microsoft typescript

TypeScript Week

Posted on .

This week on DailyJS every post is about TypeScript! The first post introduces the language, and the growing TypeScript community.

TypeScript might not be as popular as CoffeeScript, but it seems to be catching on with a highly productive niche of developers that are building interesting open source projects. TypeScript is very much of the new school of Microsoft developers: it embraces Node, open standards, open source, while building on interesting influences from Microsoft Research and .NET.

If you're excited by technologies like C# 5.0's asynchronous support and ReactiveUI, then TypeScript will help you to be more productive with JavaScript. There's even Visual Studio support! If you're from a JavaScript client-side or server-side background, however, then it might be harder to appreciate why TypeScript is interesting.

The first thing to consider is that TypeScript adopts ideas from ECMAScript 6, while compiling down to ES3. This includes features like classes, modules, and a succinct lambda syntax:

var deck = {  
  suits: ["hearts", "spades", "clubs", "diamonds"],
  cards: Array(52),
  createCardPicker: function() {
    return () => {
      var pickedCard = Math.floor(Math.random() * 52);
      var pickedSuit = Math.floor(pickedCard / 13);
      return { suit: this.suits[pickedSuit], card: pickedCard % 13 };

In this example, the lambda is introduced with () =>. This should be familiar to C# developers, but for the rest of us it feels quite new. There's a subtle difference to using function() {}, however -- lambdas capture this in a more intuitive way than standard JavaScript. In this example, this.suits is possible because the lambda binds to the containing object rather than window.

TypeScript allows you to write classes with the class keyword and inherit with the extends keyword. There's more, though: generics are supported. Again, the syntax looks like C#, using angle brackets to denote the generic type parameter:

class GenericNumber<T> {  
  zeroValue: T;
  add: (x: T, y: T) => T;

var myGenericNumber = new GenericNumber<number>();  
myGenericNumber.zeroValue = 0;  
myGenericNumber.add = function(x, y) { return x + y; };  

C# is statically typed, which means... I'm not really qualified to go into a discussion about type systems, so here's a quote from MSDN:

C# is a strongly-typed language. Every variable and constant has a type, as does every expression that evaluates to a value. Every method signature specifies a type for each input parameter and for the return value. The .NET Framework class library defines a set of built-in numeric types as well as more complex types that represent a wide variety of logical constructs, such as the file system, network connections, collections and arrays of objects, and dates. A typical C# program uses types from the class library as well as user-defined types that model the concepts that are specific to the program's problem domain.

When working with C#, the IDE is able to infer a huge amount of information about your classes and methods. It scales up nicely on large projects, which means you can be productive despite the build/run cycle.

In fact, TypeScript was inspired by the need to develop tools for using JavaScript on large projects within Microsoft. That means to use TypeScript you'll have to get used to thinking about types, but it has benefits for writing code that can be partially verified by a compiler, and adhere to contracts (defined by "interfaces").

To interoperate with JavaScript libraries, TypeScript supports hybrid types. You can even write your own declaration files that tell the TypeScript compiler how to handle a JavaScript library.

With classes, modules, lambdas, and type hints, you might be wondering how TypeScript will fit in with the future of JavaScript now that we know some of these things are coming to ES6. Apparently Microsoft have stated that TypeScript will be adapted as JavaScript changes. I don't know what kind of backwards incompatibilities this might cause, so it'll be interesting to see how they handle updates to the language specification.

I've seen a lot of negative press about Windows 8 and Microsoft's mobile efforts, but if you're completely outside of the Microsoft ecosystem then I think you should learn more about TypeScript. Microsoft have contributed to Node, and the adoption of asynchronous and reactive programming in C# has transformed how people write software for Microsoft's platforms. The developer tools, languages, and libraries are worth learning about and may help you to write better JavaScript in general. Don't write them off just because it's fashionable to complain about Modern UI!

If you're still confused about TypeScript, get started on the Wikipedia page. It introduces some history behind the language. For more about the language, see the language spec. You can also find tutorials on typescriptlang.org, and I found the handbook useful for mentally mapping between JavaScript, C#, and TypeScript.