Skip to Content
Learning TypeScript 2.x - Second Edition
book

Learning TypeScript 2.x - Second Edition

by Remo H. Jansen
April 2018
Beginner content levelBeginner
536 pages
13h 21m
English
Packt Publishing
Content preview from Learning TypeScript 2.x - Second Edition

Discriminated unions

A discriminated union (also known as tagged unions or algebraic data types) is an advanced pattern that combines string literal types, union types, type guards, and types aliases.

Discriminated unions use a type guard to narrow union types based on tests of a discriminant property (a string literal type) and furthermore extend that capability to switch statements.

The following code snippet declares three types that share a string literal property named kind:

interface Cube {    kind: "cube";    size: number;}interface Pyramid {    kind: "pyramid";    width: number;    length: number;    height: number;}interface Sphere {    kind: "sphere";    radius: number;}

We then declare the union type of the three types declared in the preceding code snippet: ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering TypeScript - Fourth Edition

Mastering TypeScript - Fourth Edition

Nathan Rozentals
Learning TypeScript

Learning TypeScript

Josh Goldberg
TypeScript for Beginners

TypeScript for Beginners

Bharath Thippireddy

Publisher Resources

ISBN: 9781788391474Supplemental Content