Sub topic 1
Types as sets of values
Prerequisites
This chapter assumes that you know basic TypeScript syntax, including type annotations, interfaces, and type aliases. You should also be comfortable with JavaScript values, functions, and arrays.
A type describes possible values
A useful model is to treat each TypeScript type as a set of possible values. A value belongs to a type when it is one of the values in that set.
For example, boolean contains true and false. The literal type "ready" contains only the string "ready". The type string contains every string, including "ready".
type Status = "ready" | "waiting";
const first: Status = "ready";
const second: Status = "waiting";
console.log(first, second);The | operator creates a union type. A union contains values from either member type. Therefore, Status contains two possible values.
An intersection uses &. It describes values that satisfy all the member types. For object types, this usually means that the value has all required properties.
type HasId = { id: number };
type HasName = { name: string };
type RecordWithIdAndName = HasId & HasName;
const record: RecordWithIdAndName = {
id: 1,
name: "Ada",
};Subsets explain assignability
Assignability is TypeScript's decision about whether a value of a source type can be used where a target type is expected.
If every value in the source set is also in the target set, the source is assignable to the target. In set terms, the source is a subset of the target.
| Source type | Target type | Assignable? | Reason | Column |
|---|---|---|---|---|
| `"ready"` | `string` | Yes | Every `"ready"` value is a string | |
| `string` | `"ready"` | No | A string might have another value | |
| `"ready" \ | "waiting"` | `string` | Yes | Both possible values are strings |
| `HasId & HasName` | `HasId` | Yes | The intersection includes an `id` |
This model explains why a narrow type can usually be assigned to a wider type, but a wide type cannot usually be assigned to a narrow type. A value typed as string might be "ready", but it might also be "failed".
Visualizing the relationship
The compiler often checks the declared type rather than the current runtime value. Even if a variable currently contains "ready", its declared type might be string, so assigning it to a "ready" target can fail.
Exercise
Why is a value of type string not assignable to a variable of type "ready"?
Show answer
The string set contains values other than "ready", so it is not a subset of the "ready" set.