Learn TypeScript

Thinking of types as sets of values

Thinking of types as sets of values

In the next lesson, we will start to think about types in terms of sets of values. This will help us diagnose type errors.

Thinking about some primitive types as sets

A type is a possible set of values. For example, number is a set of all the possible numbers, and string is a set of all the possible strings. These examples are infinite sets because there is an endless number of possible numbers and strings.

Number and string sets

A string literal type is a set of just one value. The following example is a finite set containing "Bob":

type Bob = "Bob";

String literal set

Thinking about union and intersection types as sets

A union type is also a finite set. The following example can be thought of as a set of values containing "pending" and "completed":

type Status = "pending" | "completed";
  • Let's consider the union types below and think of them as sets of values:
type OrderStatus = "pending" | "completed";
type DeliveryStatus = "completed" | "shipped";
type Status = OrderStatus | DeliveryStatus;

The image below is how we may think of the sets of values:

Union set

🤔

What value(s) will the Status type contain?

🤔

If we change the Status type to be the intersection of OrderStatus and DeliveryStatus, what value(s) will Status contain?

type Status = OrderStatus & DeliveryStatus;

Thinking about the never and unknown types as sets

Let's turn our attention to a couple of special types in TypeScript, never and unknown.

🤔

What values does the never type contain?

🤔

What values does the unknown type contain?

Type narrowing

When understanding types of variables through code paths, the word narrowed is often used to describe the type's change.

Consider the example below:

function logStatus(status: string | null) {
if (status) {
console.log(status);
}
}
  • On line 2, the type of status is string | null.
  • On line 3, the type of status is string.

We can say TypeScript has narrowed the type of status on line 3. This is because the set of values has been reduced because the null value has been removed.

Summary

Thinking of types as sets of values can help us understand them better, particularly for union and intersection types.

In the next lesson, we will see how different types can be compatible.

Did you find this lesson useful?

Share this lesson on twitter
© 2023 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more