How to force types in Array with TypeScript’s union types.

May 14, 2015

From TypeScript 1.4 we can do nice stuff with types now, with help of feature called Union Types : https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#union-types which will let you do also this sweet stuff :

ts union types

You can see this in action on this link :

http://www.typescriptlang.org/Playground

Sample snippet here :

module ArrPlayground {
    export function fn() {
        var arr: Array<boolean|string> = [];
        arr[0] = "aaa";
        arr[1] = false;
        arr[2] = 987;

        return arr;
    }
}

Basically you can now limit types that could be used in Array (all only at compile time, same rules apply as for other type checking features of TypeScript).

Enjoy. Hope this helps.


Profile picture

Written by Dušan Roštár - the "mr edge case" guy
my twitter : rostacik, my linkedin : rostar, drop me an email : here