TypeScript: More on Union Types

In the previous article, I explained the basics of union types in TypeScript.

Though union types resemble sum types of algebraic data types, they are different types. (Confusingly, sum types are sometimes also called “unions” or “disjoint unions” in some languages.). The notion of union types, A|B denotes the ordinary union of the set of values belonging to A and the set of values belonging to B, with no added tag to identify the origin of a given element.

With this in mind, let’s look at some properties of TypeScript union types:

  • Identity: A|A is equivalent to A
  • Commutativity: A|B is equivalent to B|A
  • Associativity: (A|B)|C is equivalent to A|(B|C)
  • Subtype collapsing: A|B is equivalent to A if B is a subtype of A

In sum types, A|A is different from A because it is the sum of type A and A. (either left A or right A). However, in union types, A|A is equivalent to A because there is no tag attached to make left and right ‘A’ distinct. So it is also called “non-disjoint union types” to differentiate it from “disjoint union types” of ADT.

Non-disjoint union types are different from disjoint union types in that it lacks any kind of case construct. If v is of type A|B, the only members that we can safely access on v are members that belong to both A and B. This is why we can access only weight and gears members of transport object.

interface Car {
    weight: number;
    gears: number;
    type: string;
}
interface Bicycle {
    weight: number;
    gears: boolean;
    size: string;
}
var transport: Car|Bicycle = /* ... */;
console.log(transport.type); // Error, transport does not have 'type' property

So if the constituent types of a union type have no members in common, there is nothing we can do on the union type. For example, if x is of number|string|boolean type, we can only access toString and valueOf members that are common across these three types.

Wait a minute! I’ve just mentioned that union types lack any kind of case construct. But what about the type guards of TypeScript? Isn’t it a kind of case construct that can identify the origin of an element? The answer is both yes and no. Yes, you can inspect the runtime type of a union type with type guards. But no because there is nothing special that prevents you from checking non-constituent types. For example, the following code is perfectly okay in TypeScript:

var x: number | boolean;
if (typeof x === 'number') {
    // ...
}

x is either number or boolean, but the type guard here checks if the type of x is number. In the body of if expression, TypeScript infers that the type of x is number though it never can’t be of number type. On the contrary, in programming languages with sum types, we can check only the constituent types with pattern matching.

TypeScript Function Overloads

In TypeScript, you can declare an overloaded function by declaring the function with a multiple invocation signatures.

interface Foo
{
    bar: {
        (s: string): number;
        (n: number): string;
    }
}

or

interface Foo {
    bar(s: string): number;
    bar(n: number): string;
}

The type checker of TypeScript works as expected:

var foo1: Foo = ...;

var n: number = foo1.bar('hello world'); // OK
var s: string = foo1.bar(123);           // OK
var a: boolean = foo1.bar(false);        // ERROR

However, you can’t actually define an overloaded function with multiple function definitions as in C# or Java. The compiler complains about “error TS2393: Duplicate function implementation”. This happens because the signatures of both bar functions are identical once their types are erased.

class FooClass implements Foo {
    bar(s: string): number {
        return s.length;
    }
	
    bar(n: number): string {
        return n.toString();
    }
}

is translated to

var FooClass = (function () {
    function FooClass() {
    }
    FooClass.prototype.bar = function (s) {
        return s.length;
    };
    FooClass.prototype.bar = function (n) {
        return n.toString();
    };
    return FooClass;
})();

To define an overloaded function in TypeScript, the function must be singular and perform appropriate dispatching internally using type guards.

class FooClass implements Foo
{
    public bar(s: string): number;
    public bar(n: number): string;
    public bar(arg: string | number): any 
    {
        if (typeof arg=== 'number')
            return arg.toString();
        if (typeof arg === 'string')
            return arg.length;
    }
}

When you declare a variable with FooClass, you can’t see bar(arg: string | number) method even though it is declared as public. It is automatically hidden by the more specifically typed overloads.

TypeScript’s function overloads are a bit more flexible than those of C# or Java in that an overloaded function can have different return types. Note that bar(arg: string) returns number while bar(arg: number) returns string.

TypeScript Type System: Interface Types

In JavaScript, it is common to add more members to existing objects by monkey patching. For example, jQuery UI provides its API by adding a bunch of members to the jQuery object provided by jQuery.

Interface types in conventional programming languages such as Java and C# can’t represent this idiom because interfaces can’t be modified once they are declared. So if TypeScript uses the same interface types as those languages, it could be a severe limitation to the usability of the language.

Fortunately, the designers of TypeScript language were clever enough to come up with an idea to represent this idiom in a type safe manner. This idea is simply to make interface types open, meaning you can add your own members later by simply writing another interface block with the same name.

For example, Box interface has width and height properties. But you can add scale property later by writing another interface block with scale property.

interface Box {
	width: number;
	height: number;
}

interface Box {
	scale: number;
}

var b1: Box = { width: 200, height: 180, scale: 1.0 };
var b2: Box = { width: 400, height: 360 }; // Error because scale is missing

Let’s get back to the jQuery UI example mentioned above. jQuery library declares JQuery interface initially. Later, jQuery UI also declares JQuery interface and add more members to the interface. TypeScript compiler merges these two interfaces into one JQuery interface with members from both interfaces.

/**
 * The jQuery instance members
 */
interface JQuery {
    /**
     * Register a handler to be called when Ajax requests complete. This is an AjaxEvent.
     *
     * @param handler The function to be invoked.
     */
    ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery;
    // ...
}
interface JQuery {

    accordion(): JQuery;
    accordion(methodName: 'destroy'): void;
    // ...
}

TypeScript expands this idea to a more general concept called Declaration Merging. Refer to TypeScript Handbook for more information on merging modules and merging modules with classes/functions/enums.

Setting a TypeScript Compiler Project

TypeScript is not just a standalone compiler. It provides the Compiler API and the Language Service API so that you can create your own TypeScript tools leveraging all the powerful features of TypeScript compiler.

This article will show you how to setup a project using the compiler API of the latest TypeScript compiler.

Add src/tsconfig.json

To create a TypeScript project, the first thing we need to do is to create a file named tsconfig.json. The tsconfig.json file specifies the root files and the compiler options required to compile the project.

{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "target": "ES5",
        "out": "../build/tsstyle.js",
        "sourceMap": true
    },
    "files": [
        "tsstyle.ts"
    ]
}

Add package.json

Then add the project name, version, description and dependencies to package.json file. The following package.json gets the latest version of TypeScript from the GitHub repo. It also adds gulp as a dependency as we will use gulp as our build system.

{
  "name": "tsstyle",
  "version": "0.1.0",
  "description": "tsstyle",
  "dependencies": {
    "gulp": "^3.9.0"
  },
  "devDependencies": {
    "gulp-typescript": "*",
    "typescript": "Microsoft/TypeScript"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Kwang Yul Seo"
}

Add gulpfile.js

The next thing we need to do is to create a build script. Setup gulpfile.ts as in the following to use the build settings of tsconfig.json we created above.

var gulp = require('gulp');
var ts = require('gulp-typescript');

var tsProject = ts.createProject('src/tsconfig.json', 
    { typescript: require('typescript') });

gulp.task('default', function() {
    var tsResult = tsProject.src()
        .pipe(ts(tsProject));

    return tsResult.js.pipe(gulp.dest('built/local'));
});

{ typescript: require('typescript') } makes sure that we use the latest version of TypeScript from the GitHub repo instead of the TypeScript compiler bundled with gulp.

Add type definitions

Use tsd to add type definitions.

tsd query node --action install

Implementation: src/tsstyle.ts

Add references to type definition files and import typescript module. Start implementing the code. Refer to Traversing the AST with a little linter for details.

/// <reference path="../typings/node/node.d.ts" />
/// <reference path="../node_modules/typescript/bin/typescript.d.ts" />

import {readFileSync} from "fs";
import * as ts from "typescript";

/// Code here

Visual Studio Code Integration

Add the following tasks.json file to .settings directory. When you run build task, VS Code will run gulp.

{
    "version": "0.1.0",
    "command": "gulp",
    "isShellCommand": true,
    "tasks": [
        {
            "taskName": "default",
            // Make this the default build command.
            "isBuildCommand": true,
            // Show the output window only if unrecognized errors occur.
            "showOutput": "silent",
            // use the standard tsc problem matcher to find compile problems
            // in the output.
            "problemMatcher": "$tsc"
        }
    ]
}

TypeScript Type System: Union Types

Many JavaScript libraries support taking in values of more than one type. For example, jQuery’s height and width properties take an integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).

Without union types, TypeScript definition files must represent this property as type any, effectively losing type safety. This shortcoming could be worked around in function overloads as TypeScript supports function overloads (multiple functions with same name but different argument types). However, there is no equivalent for object properties, type constraints, or other type positions.

Union types let you represent a value which is one of multiple types. You can specify the types using the new | operator.

function process(n: string|number) { /* ... */ }
process('foo'); // OK
process(42); // OK
process($('div')); // Error

In the function body of process, you can examine the type of an expression using typeof or instanceof operator. TypeScript understands these conditions and change type inference accordingly.

function process(n: string|number) {
  if (typeof n === 'number') {
    // Error because n is a number.
    console.log(n.toLowerCase());
  }
}

So far, Union types look a lot like a sum type in algebraic data type. Type A|B represents a type either A or B and you use type guards to examine the type.

However, Union types of TypeScript have more interesting properties combined with structural typing. For example, the type A|B has a property P of type X|Y if A has a property P of type X and B has a property P of type Y. Here an example taken from Spec Preview: Union types.

interface Car {
  weight: number;
  gears: number;
  type: string;
}
interface Bicycle {
  weight: number;
  gears: boolean;
  size: string;
}
var transport: Car|Bicycle = /* ... */;
var w: number = transport.weight; // OK
var g = transport.gears; // OK, g is of type number|boolean

console.log(transport.type); // Error, transport does not have 'type' property
console.log((<Car>transport).type); // OK

Because both Car and Bicycle types have weight property of number type, you can access weight property of Car|Bicycle type without using a type guard. gears property is more interesting. The type of gears is number in Car and boolean in Bicycle, so the type of gears in Car|Bicycle becomes number|boolean.

Union types also change the algorithm to find the best common type. For example, now TypeScript can infer the type of a mixed array:

var xs = [1,2,3, "hello", "world"];

In old version of TypeScript, the type of xs is {}[] because number and string have nothing in common. But with Union types, the type of xs is inferred as string|number.

In conclusion, Union types provide a succinct way to represent a value with multiple types. They help you keep “DRY principle” by removing all redundant declarations of functions, properties and type constraints.

A First Look At TypeScript Type System

TypeScript type system is just a formalisation of JavaScript types. You can represent runtime types of JavaScript statically by annotating them in the source code. But at the same time it is quite unique compared to other programming language type systems as it is optional and not “provably type safe”.

  • Optional

Because TypeScript is a strict superset of JavaScript, it must accept all legal existing JavaScript code as valid TypeScript code. This means that TypeScript can’t enforce programmers to annotate every type with type annotations.

With optional typing, you can incrementally change your existing JavaScript code into TypeScript code. As you add more type annotations, you get more help from the toolset.

  • Not “provably type safe”

TypeScript type system is not for correctness safe or performance safe because it is impossible to guarantee the correctness of JavaScript with only optional typing. Traditionally, a type system that is unsound is useless as it proves nothing.

However, TypeScript type system is still meaningful because it provides information needed to implement static analysis, code completion and refactoring capabilities in tools. So we can say that TypeScript type system is for tooling safe.

TypeScript also supports type inference and structural typing to help programmers write type annotations more succinctly. It is still evolving by introducing Generics, Tuple Type, Union Type and Type Alias. I will talk more about these in later articles.

Creating a ServerSentEventServer with ReactiveWebServer

Recently, I am working on a toy project named ReactiveWebServer. It is an event-driven web server built with Rx.

Here’s a simple web server returning “Hello World”.

using (var ws = new WebServer("http://*:8080/"))
{
    const string responseBody = "Hello World";

    ws.GET("/")
        .Subscribe(ctx => ctx.Respond(responseBody));

    Console.ReadLine();
}

The code is simple, but there is nothing new compared to other web servers such as NancyFx.

The real power of ReactiveWebServer comes from its ability to handle streaming data. For example, here’s a ServerSentEvent server implementation streaming integers every second.

using (var ws = new WebServer("http://*:8000/"))
{
    ws.GET("/events").Subscribe(ctx =>
    {
        var obs = Observable.Interval(TimeSpan.FromSeconds(1))
            .Select(t => new ServerSentEvent(t.ToString()));

        ctx.Respond(new ServerSentEventsResponse(obs));
    });

    Console.ReadLine();
}

Data streaming is made simple and easy. You just need to create an instance of IObservable<ServerSentEvents>, wrap it with ServerSentEventsResponse, and pass the result to ctx.Respond method.