With the TypeScript 2.0 release candidate, Microsoft’s typed superset of JavaScript mimics a tagged unions type capability featured in languages like Rust and Swift. Through this feature, developers can cut down on writing boilerplate code.

Daniel Rosenwasser, Microsoft program manager for TypeScript, used an example in which two types, “Circle” and “Square,” have a union type, “Shape.” In TypeScript 1.8, writing a function to get the area of Shape required a type assertions for each type, whereas TypeScript 2.0 understands how to discriminate based on the “kind” field.

[ Discover the career hacks for becoming the developer everyone wants in InfoWorld’s Deep Dive. | Keep up with hot topics in programming with InfoWorld’s Application Development newsletter. ]

“Tagged unions are an exciting new feature that brings functionality from languages like F#, Swift, Rust, and others to JavaScript while embracing the way that people write JavaScript today,” Rosenwasser said. Tagged unions make it easier to get type safety using JavaScript patterns developer would write today. “For example, libraries like Redux will often use this pattern when processing actions,” he noted.

To read this article in full or to leave a comment, please click here