This project is read-only.

Supporting sum/variant types

Topics: Language Specification
Jan 1, 2014 at 3:39 AM
Everything in TypeScript seems well-designed for me except that it doesn't support sum types. I will illustrate it in two steps to show why this may be necessary for some of us.

Step 1: Occasionally we have to accept options (a hash) to a function. Suppose we use it in the following scenario:
function foo(options) {
    if (Array.isArray(
        return;  // an array of data points
        return 1;  // user is passing a single data point
That means is of type either T or T[] (let's say T is fixed). But in TypeScript I can only express it like
function foo(options: { data: any })
because there is no such a syntax like (the bar here represents the sum type)
function foo(options: { data: T|T[] })
Using any as the type annotation here makes it accept calls of any type, not only T and T[].

Step 2: One more thing that both JS and TS annoys me is null. In TypeScript everything is nullable because Null type is the subtype of everything other than undefined (got the idea from the spec, if I remember it right). Suppose we now have sum types, and treat Null type as a standalone type just like everything else (so it is not a subtype of anything). Then we can have
function bar(x: Dog) { x.bark(); }
to ensure the call of bark will never fail because of undefined error, also for
function bar(x: Dog|Null) { x.bark(); }
the compiler can safely complains x maybe null so the programmer should at least do something (e.g. IsMissing in VB).

Of course I am pretty new to TypeScript so the discussions above may inevitably ignore some other parts of TS. Anyway I hope we can have some discussions on this topic so potentially we can make TS better :-)
Jan 1, 2014 at 4:49 PM
There's a related discussion:

and a work item on the issue tracker: