17 - Creating Union Types - Using TypeScript With React
17 - Creating Union Types - Using TypeScript With React
In this lesson, we'll learn what a union type is, how to create one and some cases where they are useful.
type A_or_B_or_C = A | B | C;
Let’s go through an example to make this clear. Let’s say we have an age variable that can be null or
numeric. How could we create a type for this? Well we can combine the number and null types in a union
type as shown below:
TypeScript
1 let age: number | null;
2 age = null; // okay
3 age = 30; // okay
4 age = "30"; // error
Close
Output 3.102s
Unioning a type with null is a common use case because data can often be null or a specific type.
How could we change the type of age so that it can be undefined as well as a number or null ? Make the
change in the code widget above.
Hide Answer
let age: number | null | undefined;
What would the string literal union type be to represent the name of a fruit where it can only be Banana,
Apple, or Pear?
Hide Answer
type Actions = { type: "loading" } | { type: "loaded", data: {name: string} }
Can you think of an area in React code where this might be useful?
Hide Answer
Object unions are useful as the type of the action parameter in a reducer function. We will use object
unions later in this course when we learn how to strongly-type the useReducer hook.
Wrap up #
The union type is a way to create useful types from existing types. If a type can be something or something
else, then a union type can be used to represent that type.
String literal unions are a way of creating narrower typed strings than a plain string. Unioning with null or
undefined is a neat way to handle data that has a specific type and is empty.
Excellent; we are getting to grips with creating more advanced types now!
In the next lesson, we will learn about a slightly different way of combining existing types to construct a new
type.
Back Next
Completed
43% completed, meet the criteria and claim your course certi cate!
Buy Certificate
Ask a Question
Report an Issue
(https://discuss.educative.io/tag/creating-union-types__creating-types__using-typescript-with-react)