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 :

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

return arr;
}
}
[/javascript]

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.

0 comments

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