Sub topic 1
Types as Sets of Values
Prerequisites
Assume you know basic TypeScript syntax, interfaces, type aliases, functions, and JavaScript objects. This chapter uses compiler errors as part of the explanation.
Types as Sets of Values
A TypeScript type can be viewed as a set of values. The type number contains numeric values. The literal type "ready" contains one value. A union contains values from either set:
type Status = "ready" | "failed";
const current: Status = "ready";
// const invalid: Status = "running"; // ErrorAn intersection contains values that satisfy every part. For example, A & B must have the properties required by both A and B.
What Assignability Means: Source and Target
Assignability asks whether a source type can be used where a target type is expected. The source is the value you have. The target is the type required by a variable, parameter, or property.
A source is assignable to a target when every operation allowed by the target is safe for that source.
interface Point {
x: number;
y: number;
}
const p: Point = { x: 10, y: 20 };The object is assignable because it contains both required numeric properties.
Structural Typing: Shape, Not Name
TypeScript usually compares object types by structure. It does not require the source and target to share an interface name.
const measured = { x: 1, y: 2, unit: "px" };
const point: Point = measured; // OKmeasured has at least the shape required by Point. Its extra property is available when using measured, but the point reference exposes only x and y.
Optional and Readonly Properties
An optional property may be absent:
interface Settings {
theme?: string;
readonly version: number;
}
const settings: Settings = { version: 1 };A readonly property cannot be changed through that reference. It affects writes more than ordinary object compatibility. It does not make the object nominal or require a special declaration.
Excess Property Checks on Object Literals
Fresh object literals receive an additional check for misspelled or unexpected properties:
const saved = { x: 1, y: 2, z: 3 };
const okay: Point = saved;
const direct: Point = { x: 1, y: 2, z: 3 }; // Error: excess property 'z'The first assignment works because saved is an existing value with the required shape. The second checks the literal directly against Point.
Exercise
Why does assigning an existing variable sometimes succeed when assigning the same object literal directly fails?
Show answer
Direct object literals receive excess property checks. Existing variables are usually checked structurally for the target's required properties.