Learn TypeScript
Understanding the discriminated union pattern
Understanding the discriminated union pattern
In this lesson, we will learn what the discriminated union pattern is and how we can use it to narrow the type of a variable.
Understanding the discriminated union pattern
The discriminated union pattern has three key parts:
- The first part of the pattern is to have a common singleton type property. A singleton type is one that contains only a single value. An example of a singleton type is a string literal. This part of the pattern is called the discriminant:
type Type1 = { ... commonName: "value1"}type Type2 = { ... commonName: "value1"}...type TypeN = { ... commonName: "valueN"}
- The second part of the pattern is to have a union type of all the singleton types used. This part of the pattern is called the union:
type UnionType = Type1 | Type2 | ... | TypeN
- The final part of the pattern is to have type guards on the common property which narrows the union type:
function (param: UnionType) { switch (param.commonName) { case "value1": // type narrowed to Type1 break; case "value2": // type narrowed to Type2 break; ... case "valueN": // type narrowed to TypeN break; }}
An example
We are going to explore the discriminated union pattern in the code editor below:
The editor contains code that is similar to what we have used in the last few lessons.
What is the discriminant property in the Person
and Organisation
types?
What is the union type?
- Add the following
switch
statement to thesayHello
function:
switch (contact.contactType) { case "person": console.log("Hello " + contact.firstName); break;}
What is the type of contact
in the console.log
statement?
- Add a branch in the
switch
statement to output "Hello {name}" ifcontactType
is"Organisation"
.
What is the type of contact
in the console.log
statement you have just added?
Nice!
Summary
The discriminated union pattern is a way of narrowing a union type. A requirement for this pattern is for the types in the union to have a common property. Conditional statements can then be used on the common property as a type guard to narrow the union type.
Good stuff!
Next up, we will test what we have learned on narrowing types with a quiz.