C# 6.0 – Index Initializers

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

After two posts of new C# features that I like I thought it would be fun to change the pace a bit and discuss one that my initial impressions leave me questioning its usefulness: index initializers. I think the reason I’m confused about this feature is that all of the examples I’ve seen around it show dictionary initialization like this:

var numbers =
    new Dictionary<int, string>
        [7] = "seven",
        [9] = "nine",
        [13] = "thirteen"

My problem with this is that C# has allowed initializing dictionaries using a very similar manner since version 3! Here’s the same dictionary initialized with the more traditional object initializer syntax:

var numbers =
    new Dictionary<int, string>
        { 7, "seven" },
        { 9, "nine" },
        { 13, "thirteen" }

So we’ve swapped pairs of curly braces for pairs of square brackets and some commas with assignments? I just don’t see the benefit. It’s not that I’m opposed to index initializers; I’m confused as to why another syntax is needed for something we’ve been able to do in almost exactly the same way for years. The hint that may clear up the reasoning comes from the CTP notes which state:

We are adding a new syntax to object initializers allowing you to set values to keys through any indexer that the new object has

Given that statement, I can see indexer initializers being more useful in conjunction with custom types. Even still, it seems like the only benefit would really be foregoing specific Add method overloads on the custom type but index initializers would still be at the mercy of said type having a compatible indexer property. Unfortunately index initializers aren’t available in the CTP so I can’t really experiment with them at this time and anything else I could say about the feature would be pure speculation.

C# 6.0 – Using Static

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

In this installment of my ongoing series covering likely C# 6 language features I’ll be covering one of the features listed as “Done” on the Language feature implementation status page: using static. The idea behind using static is to allow importing members from static classes thus removing the requirement to qualify every member of an imported class with its owner. For the F#ers reading this, using static brings open module to C#.

Consider a method that writes some text to the console:

public void DoSomething()
  Console.WriteLine("Line 1");
  Console.WriteLine("Line 2");
  Console.WriteLine("Line 3");

In this example, we’ve had to specify the Console class three times. The using static feature we can simply invoke the WriteLine method:

using System.Console;

public void DoSomething()
  WriteLine("Line 1");
  WriteLine("Line 2");
  WriteLine("Line 3");

The primary benefit in this contrived example is eliminating redundancy but consider a more practical example which makes use of some of System.Math’s members:

class Circle(int radius)
  public int Radius { get; } = radius;

  public double GetArea()
    return Math.PI * Math.Pow(Radius, 2);

Here we’ve had to qualify both PI and Pow with the Math class. Granted, it only appears twice when calculating the area of a circle but it’s easy to imagine the amount of noise it would generate in more complex computations. In these cases, using static is less about eliminating redundancy and more about letting you stay focused on the problem as you can see in this revised example:

using System.Math;

class Circle(int radius)
  public int Radius { get; } = radius;

  public double GetArea()
    return PI * Pow(Radius, 2);

With both references to the Math class removed from the GetArea function, its much more readable.

I have to admit that I’m pretty excited about this feature. I can see it going a long way toward making code more maintainable.

C# 6.0 – Primary Constructors and Auto-Implemented Property Initializers

[7/30/2015] This article was written against a pre-release version of C# 6.0. Be sure to check out the list of my five favorite C# 6.0 features for content written against the release!

[Update: 1 Oct 2014] It has been said that if something sounds too good to be true, it probably is. The adage apparently even applies to the proposed C# 6 features that I was excited about. I’m sad to say that it was announced today that primary constructors would not be part of C# 6. It also sounds like there will be some changes around readonly auto-implemented properties.

As much as I prefer working in F#, I can’t ignore the fact that most of my work is still in C#. With Visual Studio “14” now in CTP 2 with some of the C# 6.0 features, it makes sense to take a more serious look at what’s in the works or has already been implemented. As such, I’ll be spending the next few articles describing some of these features and capturing my initial thoughts about them. In this article I’ll cover auto-implemented property initializers and primary constructors. Although these are separate features I suspect they’ll often be used together so it seems appropriate to discuss them at the same time. As with any CTP, everything I examine here is definitely subject to change but information regarding language feature implementation status can be found on the Roslyn Codeplex page.

Anyone familiar with F# should immediately recognize both of these features because they’ve been available in F# for years. I think both of these features are a nice addition to C# because they have the potential to greatly reduce the language’s verbosity and bring some feature parity with F# but I still like F#’s approach better.

Auto-Implemented Property Initializers

Auto-implemented property are being enhanced in two ways: they can be initialized inline, and you can define them without a setter. With inline initialization we can provide an initial value for the auto-implemented property without having to manually set the property via a constructor. For instance, if we have a Circle class with an auto-implemented Radius property we could initialize it as follows:

public class Circle
    public int Radius { get; set; } = 0;

What’s nice about the initializer syntax is that it sets the generated backing field rather than explicitly invoking the setter through a constructor or other mechanism. This feature also allows us to define a getter-only auto-implemented property, like this:

public class Circle
    public int Radius { get; } = 0;

As much as I appreciate these enhancements and will happily embrace them when they’re available, it bugs me that the type is still required in the property definition. It would be really nice to have the C# compiler infer the type from the initializer like F# does but for now, this is a nice start.

Primary Constructors

Primary constructors provide a mechanism by which a class (or struct) can accept parameters without a formal constructor declaration by including them in the class definition. The values defined in the primary constructor are scoped to the class but their lifetime is limited to class initialization by default. This makes them perfect for setting fields or initializing auto-implemented properties. Here we include a primary constructor for the Circle class and use it to initialize the Radius property:

public class Circle(int radius)
    public int Radius { get; } = radius;

The scoping rules for the values identified in the primary constructor are one place that C#’s primary constructors differ from F#’s (yes, I prefer F#’s approach here, too). As I previously mentioned, by default the primary constructor values are available only during class initialization. This means that while you’re free to use them for initialization, you can’t reference them in any methods. For instance, if we wanted to include a GetArea method our Circle class, the following approach would be invalid:

public class Circle(int radius)
    public int Radius { get; } = radius;

    public double GetArea()
        return Math.PI * Math.Pow(radius, 2);

It would be really nice if we could include an access modifier or attribute instructing the compiler to automatically generate a field but for now, it looks like we’ll have to make due with initialization scoping.

For cases where you need to do more than some basic initialization (such as parameter validation), it’s possible to define a primary constructor body by wrapping the statements in a pair of curly braces (of course, more braces) within the type definition.

As with the auto-implemented property initializers, I really appreciate this feature but wish it would go a bit further. Generally speaking, though, I see this as a positive feature for the language.

My Next Language – Results

Last week I asked my social media network to help choose my destiny by suggesting which language I should study next. In all, I received 15 responses. Thanks to everyone that contributed to this.

When I put the survey together I hadn’t completely decided how I’d select a winner. Would I select based on the number of votes or would there be a really compelling reason to select something with only a single vote? After inspecting the responses, it looks like Haskell is the clear winner. To be honest, I was really hoping to get more votes and reasons for Erlang but it’s really hard to ignore the fact that Haskell received a third of the votes. What really surprised me was the number of “Other” votes and the languages that were suggested.

For those interested, I’ve listed the results along with comments below. Now to find some time to start studying Haskell!


Language Survey Results


  • Pure functional is a natural next step after mostly functional F#
  • Going from Haskell to F# is frustrating. But the other way around is actually compelling
  • Typeclasses/-kinds, purity, better type inference and pattern matching, higher-kinded/ranked polymorphism, lean syntax.


  • Rust – Speed of C, but more safe. Language is still under development, so you could go 2/2 on being a hipster.
  • Idris/Coq/Agda – Dependent types
  • Elixir – Erlang on steroids/for the masses.
  • Rebol – Rich built-in types, homoiconicity, consistency, cross-platform, small, zero-install just download and run, super easy GUI development built-in (at least Rebol 2.7..) and then you can write a book on it too!


  • Market demand
  • Popular choice among UNIX crowd, has a .NET implementation, can show how people unfamiliar with .net interact with windows with it.


  • Immutable by default
  • Let it fail thinking vs catch-all errors
  • Functional


  • Ignore the rails stuff, ruby is a wonderful language with a lot of interesting features (modules, execution model, monkey patching aka nothing is closed, blocks).


  • No comments

TypeScript: Bringing Sanity to JavaScript

TypeScriptAs much as I’d prefer to be working in F#, I’ve found myself doing quite a bit of JavaScript lately. I’m hardly a JavaScript expert but I like to think my skills are above average (although that could merely be wishful thinking). I won’t deny that JavaScript has its problems but I think that it has traditionally been maligned by things that aren’t necessarily the language’s fault; for instance, DOM inconsistencies are hardly under JavaScript’s control. Generally speaking, I really do enjoy working with JavaScript. That said, there are things such as prototypal inheritance that I always struggle with and I know I’m definitely not alone. That’s why I decided to take a look at TypeScript now that it has finally earned a 1.0 moniker.

By introducing arrow function expressions, static typing, and class/interface based object-oriented programming, TypeScript brings sanity to JavaScript’s more troublesome areas and gently guides us to writing manageable code using familiar paradigms. Indeed, writing TypeScript feels almost the same as writing C# (with a dash of Java) which is hardly a surprise given that its lead architect is Anders Hejslberg.

If you’re currently working primarily with the Microsoft stack, adding TypeScript to your environment is easy. Because TypeScript is a proper superset of JavaScript all of your existing JavaScript is already valid TypeScript. What’s more is that while the TypeScript compiler emits JavaScript, it also produces a .map file which allows you to debug using the original TypeScript source!

In this article, I’ll introduce a number of what I think are TypeScript’s most important features giving a brief overview of each. This isn’t intended to be a comprehensive survey of the language but hopefully it will give you enough information to whet your appetite.

Functional Goodness

As a functional guy, I strongly believe that JavaScript is at its best when its functional nature is embraced. TypeScript includes a few features that make functional programming more accessible.

Arrow Function Expressions

Arrow function expressions are hardly the most important aspect of TypeScript but I like them so much and will be using them throughout this article so I thought it best to describe them up front.

One of the things that bothers me about JavaScript is its lack of lambda expressions. JavaScript’s anonymous functions certainly serve the same purpose but oftentimes they introduce a lot of noise that can obscure the function’s logic. Consider a simple anonymous function for calculating the area of a circle:

function (radius) { return Math.PI * Math.pow(radius, 2); };

In this example, only about 60% of the code is actually what I’d consider useful; the rest is syntactic noise. Toss this form into a call to a higher-order function and the logic is further obfuscated. This has been especially bothersome since I’ve gotten so used to lambda expressions in C# and F#. ECMAScript 6 has a proposed arrow syntax that closely resembles C#’s lambda expressions but ECMAScript 6 adoption is a long way off. Fortunately, with TypeScript you can use it today. In TypeScript, you could redefine the above function like this:

radius => Math.PI * Math.pow(radius, 2);

The arrow function syntax is equivalent to the traditional syntax (the compiler actually expands it to the traditional syntax) but the amount of useful code is closer to 90% – a significant improvement!

Optional and Default Parameters

One aspect of JavaScript that I consider to be both a blessing and a curse is its flexibility with function parameters. On one hand, it’s nice to be able to pass any number of values to a function and access them via the arguments pseudo-array. On the other hand, if I’ve taken the time to explicitly list each parameter, I should reasonably expect that a value will be supplied for each yet JavaScript offers no such guarantee. TypeScript enforces that the proper number of arguments are supplied. Let’s look at a simple function for formatting a typical American name:

function formatName(first : string, last : string, middle : string) {
    return last + ", " + first + " " + middle;

Unfortunately for our function, not everyone has a middle name so if we try to invoke the function but supply values for only first and last, the compiler will warn that it cannot select an overload. To work around this, we can define middle as either an optional parameter or a default parameter.

To make middle an optional parameter, we simply need to append a question mark to the parameter name. We can then handle the parameter appropriately within the function body as shown:

function formatName(first : string, last : string, middle? : string) {
    return last + ", " + first + (middle ? " " + middle : "");

Alternatively, to make middle a default parameter we simply need to replace the type annotation with an assignment as follows:

function formatName(first : string, last : string, middle = "") {
    return last + ", " + first + " " + middle;

The compiler infers the proper type from the assignment and we’re guaranteed to have a value (unless someone passes null, of course).

Function Overloading

Optional and default parameters are nice for simple scenarios but for more complex scenarios we can turn to function overloading. Because JavaScript doesn’t support overloading, TypeScript’s overloading capabilities are rather limited and are quite different from what you might expect.

TypeScript’s function overloads have two parts, the overload signatures, and the implementation. The caveat is that the compiler must be able to resolve each overload signature to the implementation signature. Interestingly, each overload signature can resolve to an empty signature thus, I’ve (so far) found it most convenient to provide the implementation as a parameterless function and resort to the traditional JavaScript approach of using the arguments pseudo-array to determine what was supplied based on the overload signatures. To see this in action, let’s look at an overload approach to the simple name formatting function we saw in the previous section:

function formatName(first : string, last : string);
function formatName(first : string, last : string, middle : string);
function formatName() {
    var first = arguments[0];
    var last = arguments[1];
    var middle = arguments.length > 2 ? arguments[2] : undefined;
    return first + ", " + last + (middle ? " " + middle : "");

By virtue of the overload signatures, we can invoke the formatName function with either 2 or 3 arguments. The implementation knows to expect both the first and last names so it assigns them to names unconditionally. The implementation also knows that it may or may not receive a middle name so it conditionally sets that value before concatenating and returning the values.

Built-in Types

With a name like “TypeScript” you probably correctly guessed that the type system plays a significant role within the language. TypeScript shares a number of common types with JavaScript. For the purposes of this article, I’ll assume you’re already familiar with the common types such as Boolean, Number, String, Null, and Undefined and focus on what TypeScript adds.


JavaScript is a dynamically typed language. Although dynamic typing is convenient for simple applications, it often leads to confusion and fragility in more complex systems. TypeScript deviates from JavaScript by using static typing.

The TypeScript language reference states that static typing is optional but this seems a bit misleading. In TypeScript, all types derive from the Any type thus, every type is compatible with Any. In this sense, the Any type is much like Object in .NET or Java as shown next:

var x: any = 10;
x = "a";
x = true;

Here we’ve defined the variable x to be of type Any by including a type annotation in the definition and setting its initial value to 10. We then change the value to a string before finally settling on a Boolean.

Where Any differs from Object (and where I think the statement about optional static typing originates, though that’s pure speculation) is that a value of type Any can be assigned to any other type. The following code shows this principle in action:

var x: number = 10;
var y: any = "a";
x = y;

In this example we define two variables, x and y. Here, x is explicitly defined as Number while y is defined as Any. On the final line, we assign y to x and the TypeScript compiler happily complies despite the differing types.


The Void type is similar to the void type in C# in that it is generally used as a function’s return type to indicate the function has an effect as Void indicates no particular value. Where TypeScript’s Void type differs from that of other languages is that Void is also the base type for both null and undefined (null is also a subtype of every type other than undefined) so it’s technically possible to define a variable of type Void but doing so is rather pointless.


TypeScript includes first-class support for enumerations through C#-like enum declarations.


TypeScript’s enumerations let you associate a series of labels to known numeric values thus avoiding “magic numbers.” A nice thing about TypeScript enumerations is that because they’re subtypes of Number, they can be used interchangeably with Number but the TypeScript compiler protects against assigning the wrong enumeration type. Here’s an example of a simple enumeration that defines some shapes:

enum Shapes {

The previous sample follows the default behavior of implicitly assigning zero-based sequential values to the labels such that None is 0, Circle, is 1, and so on. Just as in C#, you can override this default behavior by explicitly providing values inline as follows:

enum Shapes {
    None = 0,
    Circle = 10,
    Triangle = 20,
    Rectangle = 30

Now, instead of being automatically associated with a value, each label is explicitly assigned. Should any label not have an explicitly associated value, the default sequential implicit association will be used.

Despite their syntactic similarities with C#, TypeScript enumerations are actually quite different constructs. The way a TypeScript enumeration is represented in JavaScript is fascinating and highlights how flexible JavaScript truly is. Here’s the JavaScript representation of the Shapes enumeration using the default (generated) values:

var Shapes;
(function (Shapes) {
    Shapes[Shapes["None"] = 0] = "None";
    Shapes[Shapes["Circle"] = 1] = "Circle";
    Shapes[Shapes["Triangle"] = 2] = "Triangle";
    Shapes[Shapes["Rectangle"] = 3] = "Rectangle";
})(Shapes || (Shapes = {}));

The first time I saw this code it took me a little while to understand what it was doing but it’s actually quite simple once you recognize that it relies heavily on the fact that the assignment operator returns a value. At its heart, initializing the enumeration involves an immediate function which dynamically creates two properties for each named value. The first property is named for the case it represents and is assigned the case value (Shapes[“None”] = 0). The second property is named for the case value (via the nested assignment) and is assigned the case name (Shapes[Shapes[“None”] = 0] = “None”). These dual properties establish a sort of bi-directional relationship allows you to fairly easily retrieve either the name or value via the property indexer syntax. For instance, if you wanted to get the name “Circle” you’d write this:


Computed Members

When the case values are known constants (either explicitly supplied or implicitly generated), the members are said to be constant members. Where TypeScript enumerations get really interesting is that they can exploit the underlying JavaScript’s dynamic nature such that the explicitly associated values don’t need to be constants! Instead, each case can be based on a computation so long as that computation results in a number. For instance, we could define a Circles enumeration with each label associated with different computed areas like this:

var getArea = r => Math.PI * Math.pow(r, 2);

enum Circles {
    Small = getArea(1),
    Medium = getArea(5),
    Large = getArea(10)

The TypeScript compiler behaves differently when resolving computed members than it does when resolving constant members. With constant members, the compiler replaces the member reference with the constant value. Conversely, computed members are left as member references.

Type Annotations and Inference

Like any language with static typing, you need a way to inform the compiler what type to expect. TypeScript achieves this through F#-like type annotations on variable declarations as shown next:

var x : number = 10;
var y : string = "ten";

Here we’ve defined two variables, x and y, and annotated them to be of types number and string, respectively. Constantly telling the compiler what type to expect gets pretty tedious (it’s one of my main gripes about C#) but fortunately, TypeScript includes a rather robust type inference system which often makes explicit annotations unnecessary. Here are the same definitions without the type annotations:

var x = 10;
var y = "ten";

While these may look like traditional JavaScript definitions, they are in fact strongly typed. What’s happened is that the compiler inferred Number and String from the respective values as evidenced by hovering over the name in Visual Studio to reveal the appropriate type names.

TypeScript’s type inference can also work contextually on function parameters as shown in this example adapted from the TypeScript handbook:

window.onmousedown = e => console.log(e.button);

The TypeScript compiler knows about onmousedown so it is able to infer that e is of type MouseEvent. Interestingly, despite TypeScript’s typically bottom-up approach to type inference, function parameters are inferred to be of type Any. Let’s take another look at the getArea function introduced in the earlier Circles example, to see this in action (note that this example uses another TypeScript feature, the arrow function; we’ll take a closer look at arrow functions in the Functional Goodness section a bit later):

var getArea = r => Math.PI * Math.pow(r, 2);

If we were to hover over getArea in Visual Studio, we’d see that it’s signature is (r: any) => number which indicates that the sole parameter, r, is of type Any and getArea’s return value is Number. Unfortunately, TypeScript’s type inference capabilities aren’t quite as strong as F#’s so despite Math.pow requiring a Number, r is still inferred to be Any. To improve getArea’s type safety we should revise it to identify the parameter type through an annotation like this:

var getArea = (r : number) => Math.PI * Math.pow(r, 2);

Now Visual Studio will correctly report the function’s type as (r: number) => number.


JavaScript has always been an object-based language. The problem with being object-based rather than object-oriented is that developers tend to want to treat it as an object-oriented language but get frustrated when core OO concepts like inheritance and encapsulation don’t work the same way as they do in more traditional OO languages. The name JavaScript has never helped distinguish it, either. It’s often not that these things can’t be done in JavaScript or even that they’re difficult, it’s just that JavaScript’s approach is so foreign that developers often find them confusing.

Much of that confusion stems from the fact that objects aren’t really objects in the way that traditional OO developers think of them. Instead, JavaScript objects are dictionaries (or hashes, if you prefer) with some additional syntactic support. Sure, we can define functions that serve as constructors, nest values, and even reference something in an instance via the this identifier but all we’re really doing is defining a series of key/value pairs. This is especially apparent when using object literals.

TypeScript addresses disconnect this through formal classes that somewhat resemble C# classes. For instance, here’s a simple class that represents a circle:

class Circle {
    radius : number;

    constructor(radius : number) {
        this.radius = radius;

    getArea() {
        return Math.PI * Math.pow(this.radius, 2);

The traditional OO conventions should be pretty easy to spot in the Circle class. First, we have a field named radius, next is a constructor which accepts the radius, and finally there’s a method called getArea.

Aside from following a more conventional approach, TypeScript classes ensure that the JavaScript definitions are properly established on the object. For example, the getArea method is associated with Circle’s prototype rather than Circle itself thus facilitating reuse and inheritance.

Access Control

In TypeScript, class members are public by default but can be made private by including the private access modifier. It’s important to note though, that this access control does not extend beyond TypeScript’s boundaries into the compiled JavaScript;. Because each member is directly associated with the object, anything defined as private will still be a property of the object and thus, accessible via JavaScript. It’s also important to note that TypeScript has no concept of protected members.

Accessors (Properties)

Fields will often be sufficient for associating data with an object but should you require more granular control over how values are accessed or modified, you can use the get and set accessors in conjunction with a backing field. Let’s revise our Circle class to use this approach:

class Circle {
    private _radius: number;

    constructor(radius: number) {
        this._radius = radius;

    get radius() { return this._radius; }
    set radius(value) { this._radius = value; }

    getArea() {
        return Math.PI * Math.pow(this._radius, 2);

Now the Circle class has a private _radius field. Access to that field is controlled through the get and set radius functions. If we wanted to make the radius value read-only then we could omit the set function but this will still control access to the _radius value within the confines of TypeScript.


Like classes in more traditional OO languages, TypeScript classes support methods. TypeScript methods are just regular functions with a streamlined syntax. One notable aspect of defining functions as methods as opposed to fields is that the compiler attaches methods to the object’s prototype rather than an individual instance which plays more nicely with JavaScript inheritance.

Since methods are just functions, it’s possible to overload them in the same manner as a function.


TypeScript classes are initialized through constructor functions. You can either define your own constructor function or rely on the default constructor functions provided by the compiler. We’ve already seen an example of a TypeScript constructor so I won’t repeat it here.

Automatic Constructors

If you don’t define a constructor function, the compiler will generate one automatically for you. In many cases, the automatic constructor function will have no parameters and perform no initialization actions beyond member variable initialization. However, if the class is derived from another class, the automatic constructor will accept the same parameters as the base class’ constructor and pass the arguments on to the base class before initializing member variables.

Custom Constructors

To create a custom constructor function we simply define a function named “constructor” along with any parameters we want to accept as shown in the Circle class above. Like functions and methods, it’s possible to overload constructors.

Parameter Properties

As a final note about TypeScript constructors, if you specify an access modifier (public or private) for a parameter, that parameter will automatically become a field on the class. This approach is much like F#’s (or C# 6’s) primary constructors. We’ll see an example of this a bit later when we look at interfaces.


As I mentioned at the beginning of the article, prototypal inheritance is something I typically mess up when coding straight JavaScript. It’s not necessarily that prototypal inheritance is hard, it’s just that I typically forget some step. Rather than relying on search engines memory to get it right, TypeScript provides a familiar, Java-like inheritance syntax.

Central to TypeScript’s inheritance model is the extends keyword which allows you to specify the base class as shown in the following sample:

class Shape {
    description: string;
    constructor (description : string) {
        this.description = description;
    getArea() { return NaN; }
    toString() { return this.description; }

class Circle extends Shape {
    radius : number;

    constructor (radius: number) {
        this.radius = radius;
    getArea() {
        return Math.PI * Math.pow(this.radius, 2);
    toString() {
        var area = this.getArea();
        return super.toString() + " (" + area.toString() + ")";

In the preceding code, the Circle class extends the Shape class and overrides both of its methods (note that TypeScript has no concept of abstract members). Because the Circle class has a custom constructor we needed to explicitly invoke Shape’s constructor. Had we used an automatic constructor, the compiler would have handled this detail for us.

Derived classes can access the base class’ public members via the super identifier as shown in the Circle class’ toString override. Because the TypeScript compiler handles the details of ensuring that the correct execution context (this) is used, we could just as easily have foregone overriding toString by including the call to getArea in the Shape class but I thought it would be more useful to see the super identifer in action.

Static Members

Although TypeScript doesn’t include the notion of an static class (modules fill that role as we’ll see a bit later), classes can have static members. To make a member static, simply prefix the definition with the static modifier. The following snippet shows a class with a static method:

class CircleGeometry {
    static getArea(circle) {
        return Math.PI * Math.pow(circle.radius, 2);


Interfaces in TypeScript serve much the same purpose as interfaces in traditional OO languages in that they specify a contract to which an object must adhere. It’s important to recognize that TypeScript’s interfaces are purely logical constructs. Interfaces exist only within the TypeScript sandbox to help enforce type safety; you won’t find any traces of them in the compiled JavaScript. That said, I also consider them to be one of TypeScript’s most powerful and compelling features because of how they embrace the underlying JavaScript’s dynamic nature to improve type safety with code not only within your project but from outside as well.


Interface definition follows the familiar pattern from other traditional OO languages. Here’s how we could define an interface to represent an object that implements a getArea method:

interface Shape {
    getArea () : number;

The Shape interface defines a single member: a function named “getArea” that accepts no parameters and returns a number. This ensures that whenever we have an instance of something that implements the Shape interface, the interface guarantees that instance will have a getArea function.

Implementing with Classes

Implementing interfaces with classes via the implements keyword is perhaps the most familiar way interfaces are used. For example, we could define a Circle class that implements the Shape interface as follows:

class Circle implements Shape {
    constructor(public radius : number) {} // <-- note the public modifier; I told you we'd see it later!
    getArea() { return Math.PI * Math.pow(this.radius, 2); }

As you can see, defining a class that implements an interface is almost identical to a normal definition – all we had to do was identify the interface via the implements keyword. Should you need to implement multiple interfaces, simply delimit the names with commas.

Type Compatibility

What’s interesting about TypeScript interfaces is that an object’s type compatibility is based on object structure rather than explicit definition. This greatly increases the power of TypeScript’s interfaces because it means that types including object literals or externally defined types can satisfy an interface’s requirements by virtue of having the correct members. Consider a function which simply prints out a shape’s area:

function writeArea (shape : Shape) {
    document.write("The shape's area is: " + shape.getArea() + "<br />");

Here we’ve constrained the shape parameter to types that implement the Shape interface. While we certainly could pass along an instance of the Circle class we defined in the last section, it’s much more interesting to use an object literal! First, we’ll create the function that creates and returns the literal:

function createCircle (radius : number) {
    return { getArea: () => Math.PI * Math.pow(radius, 2) };

The createCircle function accepts the radius and returns an object literal with a single member: a getArea function. If we invoke inspect createCircle’s signature, we’ll find that its return type is Any. However, if we invoke the writeArea function, passing the result of createCircle as follows, the compiler is perfectly happy:

writeArea (createCircle(5));

The fact that the object literal includes the getArea function is enough to satisfy the compiler. If we wanted to get more explicit and further prove how the Shape interface is satisfied, we can annotate the createCircle function with a return value (rather than relying on the type inference) like this:

function createCircle (radius : number) : Shape {
    return { getArea: () => Math.PI * Math.pow(radius, 2) };

Even with the type annotation in place, the compiler recognizes that the object literal meets the requirements defined by the interface. Used like this, object expressions are conceptually similar to F#’s object expressions in that they can be created ad-hoc but still satisfy the type requirements.

Describing Functions

One of my favorite TypeScript features is that interfaces can also represent function signatures! Function signatures can get quite verbose, especially when dealing with generics (something I’m not covering in this article beyond this brief glimpse). To improve maintainability, you might consider leveraging this feature. For now, we’ll stick with a simple example of how you might define an interface that represents a predicate:

interface Predicate<T> {
    (item: T): boolean;

Using this form we’re not defining which members must be implemented, we’re defining the arguments and return type of a function! Now, rather than repeating the signature everywhere, we can simply use the interface name instead as shown in this filter function:

function filter<T> (source : T[], callback : Predicate<T>) {
    var result = [];
    for(var i = 0; i < source.length; i++) {
        var value = source[i];
        if (callback(value)) result[result.length] = value;

    return result;

If we wanted to use this function to filter out all of the odd numbers from an array we could write:

var evenNumbers =
        [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144],
        i => i % 2 === 0);

Notice how we didn’t need to do anything special with the supplied function – we simply passed it as we would any other argument. The compiler even inferred the correct type parameter for the filter function and, by extension, the Predicate interface!


Modules provide a convenient mechanism for grouping related code elements while providing some degree of encapsulation and access control. The primary benefit of organizing code in this manner is to avoid polluting the global namespace with miscellaneous types and functions, thus reducing the likelihood of naming conflicts. In many ways they’re very much like modules in F# or static classes in C#. Let’s take a look at how to define a module continuing with our theme of circle geometry:

module CircleGeometry {
    export function getArea(radius : number) {
        return Math.PI * Math.pow(radius, 2);
    export function getCircumference(radius : number) {
        return 2 * Math.PI * radius;

The CircleGeometry module defines two functions, getArea and getCircumference. By default, module members are private so in order to access these functions from outside the module we export them using the export keyword. With the module in place, we’re free to invoke its functions with a qualified name like this:


Despite their similarity to static classes, module are represented quite differently in the compiled JavaScript. To see just how different modules and classes are, let’s create a functionally equivalent class with static members and compare the generated JavaScript. First, here’s the class definition:

class CircleGeometry {
    static getArea(radius : number) {
        return Math.PI * Math.pow(radius, 2); 

    static getCircumference(radius : number) {
        return 2 * Math.PI * radius;

This results in the following JavaScript:

var CircleGeometry = (function () {
    function CircleGeometry() {
    CircleGeometry.getArea = function (radius) {
        return Math.PI * Math.pow(radius, 2);

    CircleGeometry.getCircumference = function (radius) {
        return 2 * Math.PI * radius;
    return CircleGeometry;

The generated JavaScript isn’t particularly complicated; it assigns the result of an immediate function to the name CircleGeometry. The immediate function creates a void function called CircleGeometry (which would serve as a constructor function should we want to create an instance), sets the two functions as properties of that function, and returns it. Now, compare that with what’s generated for the module we defined earlier:

var CircleGeometry;
(function (CircleGeometry) {
    function getArea(radius) {
        return Math.PI * Math.pow(radius, 2);
    CircleGeometry.getArea = getArea;

    function getCircumference(radius) {
        return 2 * Math.PI * radius;
    CircleGeometry.getCircumference = getCircumference;
})(CircleGeometry || (CircleGeometry = {}));

Again, the generated JavaScript isn’t very complicated but this time, the behavior is much different. Here, a variable called CircleGeometry is declared but not assigned. Next, an immediate function is defined and invoked, passing either an existing CircleGeometry object or a new object (via the assignment operator’s return value) that will expose the functions as properties. Inside the immediate function’s body we can clearly see both the getArea and getCircumference but, rather than being directly assigned to properties on the supplied object, the functions are defined as, well, functions! It’s only after the function definitions that they’re assigned to properties on the supplied object via name. This difference may appear subtle but it means that the immediate function for the module definition is serving as a closure thereby hiding the actual implementations. A script certainly could reassign the properties but it wouldn’t necessarily have access to anything else defined within the closure, particularly not the private members.


As a super set of JavaScript, TypeScript is by no means a perfect language. It carries JavaScript’s legacy (both good and bad) but I see this as more of a strength than a weakness because the compiler takes advantage of many of JavaScript’s best features and wrangles them into more familiar object oriented and functional patterns. Taken together, the language features described in this article should lead to simpler, more maintainable code which is as important as ever as application complexity continues to increase.

Upcoming Event: Iowa Code Camp

I’m excited to have been selected to speak at Iowa Code Camp on July 19th. The organizers have put together what should be a great event with some really strong speakers.

I’ll be speaking about – you guessed it – F#! This is my introductory talk, Breaking Free with Managed Functional Programming, so if you’re in the area and want to learn my F# is getting so much attention, be sure to stop in.

Breaking Free at IndyMobileDev

On June 3, I presented Break Free with Managed Functional Programming: an Introduction to F# at the Indianapolis Mobile .NET Developers group. Brad Pillow was kind enough to record the entire presentation and post it to YouTube. The slides are a bit hard read in the video but I’ve posted them to SlideShare (and embedded them below the video) so you can follow along.