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

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 :

<br />
module ArrPlayground {<br />
    export function fn() {<br />
        var arr: Array&lt;boolean|string&gt; = [];<br />
        arr[0] = &quot;aaa&quot;;<br />
        arr[1] = false;<br />
        arr[2] = 987;</p>
<p>        return arr;<br />
    }<br />
}<br />

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.