Quantcast
Channel: TypeScript – rostacik .net
Viewing all articles
Browse latest Browse all 14

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

$
0
0

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.


Viewing all articles
Browse latest Browse all 14

Trending Articles