Sub topic 1
Types as sets of values
Prerequisites
This chapter assumes you already know the following:
- Basic TypeScript syntax: type annotations, interfaces, and type aliases.
- How functions, objects, and arrays work in JavaScript.
- What a common compiler error looks like, such as "Type 'string' is not assignable to type 'number'".
You do not need to know anything about variance or generics yet. Later chapters cover them.
Why start with sets
Every assignability rule in TypeScript can be traced back to one idea: a type is a set of values. When you write const x: number, you are saying that x may hold any value from the set of numbers. When the compiler rejects an assignment, it is telling you that some value in the source set is not in the target set.
This model gives you a way to predict compiler behavior without memorizing a list of rules. If you can describe the two sets, you can usually say whether the assignment compiles.
Small sets and large sets
Some types contain exactly one value. These are literal types.
type One = 1;
type Hello = "hello";
type Yes = true;
const a: One = 1; // OK: 1 is the only member of the set
const b: One = 2; // Error: Type '2' is not assignable to type '1'A union lists the members of a larger set.
type Direction = "up" | "down" | "left" | "right";
let d: Direction = "up"; // OK
d = "sideways"; // Error: not one of the four membersDirection has four members. string has infinitely many. Every member of Direction is also a member of string, so Direction is a subset of string.
const dir: Direction = "left";
const s: string = dir; // OK: every Direction value is a string
const t: string = "anything";
const back: Direction = t; // Error: not every string is a DirectionThe first assignment compiles because the source set is contained in the target set. The second fails because the source set contains values that the target does not.
The core rule
Assignability, in set terms, comes down to one statement:
> A source type S is assignable to a target type T when every value in S is also in T.
In other words, S must be a subset of T (or equal to it). The chapter on the assignability relation formalizes this. For now, treat it as a mental check you can run on any assignment: "Could the source hold anything the target would not accept?" If so, the compiler reports an error.
Objects are sets too
Object types also describe sets. The type { name: string } is the set of all values that have a name property holding a string. It does not say the value has nothing else.
interface Named {
name: string;
}
interface Person {
name: string;
age: number;
}
const p: Person = { name: "Ada", age: 36 };
const n: Named = p; // OKHere is the part that surprises many people. Person has more properties, yet it is the smaller set. Every Person has a name string, so every Person is also a Named. But many Named values have no age, so they are not Person values. Adding requirements to a type shrinks its set. This is why a more detailed type can be used where a less detailed one is expected.
const onlyName: Named = { name: "Grace" };
const person: Person = onlyName; // Error: Property 'age' is missingThe next chapters explain how structural typing, excess property checks and weak type detection refine this picture. The base idea stays the same.
Unions grow the set, intersections shrink it
A union combines the sets of its members, so it is larger than each member. An intersection keeps only the values that belong to all of its members, so it is smaller.
type A = { a: number };
type B = { b: number };
type Either = A | B; // values that are an A, or a B, or both
type Both = A & B; // values that are an A and a B
const both: Both = { a: 1, b: 2 };
const either: Either = both; // OK: Both is a subset of Either
const alsoA: A = both; // OK: Both is a subset of A
const wrong: Both = either; // Error: an Either might lack a or bNotice that Both is assignable to everything on this list. A subset can always be used where a superset is expected, and Both is a subset of A, B and Either.
The two extremes: the empty set and the full set
Two types sit at the ends of the scale.
neveris the empty set. It has no values, so it is a subset of every other set. That is whyneveris assignable to every type.unknownis the set of all values. Every other set is a subset of it. That is why every type is assignable tounknown.
function fail(): never {
throw new Error("unreachable");
}
const x: string = fail(); // OK: an empty set is a subset of string
const y: unknown = "text"; // OK: string is a subset of unknown
const z: string = y; // Error: unknown is not assignable to stringThe type any does not fit this picture. It is an escape hatch that turns off the check for the values it touches, which is why it is covered separately in a later chapter.
Where the set model stops being exact
The set model explains most rules, but you should know its limits so that you do not over-apply it.
- Types are checked by shape, not by listing values. The compiler does not enumerate set members. It compares property types and signatures. The set model is a way to reason about the result, not a description of the algorithm.
- Fresh object literals get extra checks.
{ name: "Ada", age: 36 }assigned directly toNamedis rejected for the extraageproperty, even though aPersonvalue would be accepted. The set model alone would allow both. The excess property chapter covers this. - Some rules are deliberately unsound. TypeScript accepts a few assignments that a strict subset check would reject, such as array covariance, because strictness there would make everyday code painful. A later chapter lists them.
Common mistakes
- Reading "more properties" as "bigger type". More required properties make a smaller set, which is why
Personis assignable toNamed. - Assuming a literal stays a literal. A value like
"fast"assigned to a mutable variable widens tostring, which is a larger set. The widening chapter explains when this happens. - Treating
unknownlikeany. Both accept every value, but onlyunknownforces you to narrow before use.
Exercises
Exercise
Given type Small = "a" | "b" and type Big = "a" | "b" | "c", which of const x: Big = smallValue and const y: Small = bigValue compiles, and why?
Show answer
Only the first one compiles. Small is a subset of Big, so every Small value is also a Big value. Big contains "c", which is not in Small, so a Big value cannot be assigned to Small.
Exercise
interface Named { name: string } and interface Person { name: string; age: number }. Which type describes the larger set of values, and which direction of assignment is allowed?
Show answer
Named describes the larger set, because it has fewer requirements. A Person can be assigned to Named, since every Person has a name. A Named cannot be assigned to Person, because it may lack age.
Exercise
Why is never assignable to every type, while unknown is assignable only to unknown and any?
Show answer
never is the empty set, and an empty set is a subset of every set. unknown is the set of all values, so it is a subset only of itself (and any, which accepts everything). Any other target set would leave out some values that unknown can hold.