Sub topic 2
What Assignability Means: Source and Target
Prerequisites
This chapter assumes basic TypeScript syntax, including type annotations, interfaces, and type aliases. You should also be familiar with JavaScript objects and compiler errors.
The source and the target
Assignability is TypeScript’s way of answering this question:
> Can a value of one type be used where another type is expected?
The type of the value being used is the source type. The type required by the receiving location is the target type.
interface User {
id: number;
name: string;
}
const candidate = {
id: 1,
name: "Ada",
};
const accepted: User = candidate;
function greet(user: User): string {
return `Hello, ${user.name}`;
}
console.log(greet(accepted));Here, candidate is the source. User is the target. The assignment succeeds because candidate has the properties that User requires, with compatible types.
The direction matters:
interface BasicUser {
name: string;
}
interface DetailedUser {
name: string;
email: string;
}
const detailed: DetailedUser = {
name: "Ada",
email: "[email protected]",
};
const basic: BasicUser = detailed; // OKA DetailedUser can be used as a BasicUser because it contains everything a BasicUser needs. The reverse assignment would fail because a BasicUser might not have an email property.
Assignability as sets of values
A useful model is to imagine that every type describes a set of permitted values. DetailedUser describes values with both name and email. BasicUser describes values with at least name.
The source is assignable to the target when every value allowed by the source is safe to use as a target value.
Type compatibility is structural
TypeScript usually compares structure rather than type names. This is called structural typing. Two independently declared types are compatible when their required members are compatible.
type Coordinates = {
x: number;
y: number;
};
interface Point {
x: number;
y: number;
}
const coordinates: Coordinates = { x: 10, y: 20 };
const point: Point = coordinates; // OKThe names Coordinates and Point do not need to match.
A fresh object literal receives an additional excess-property check:
interface User {
id: number;
name: string;
}
const candidate = { id: 1, name: "Ada", active: true };
const accepted: User = candidate; // OK
// @ts-expect-error: active is not declared in User
const rejected: User = { id: 1, name: "Ada", active: true };The variable assignment succeeds because the existing value has the required shape. The fresh literal is rejected because it contains the unexpected active property.
Exercise
In const result: { name: string } = { name: "Ada", age: 36 }, what are the source and target, and why can the assignment fail?
Show answer
The object literal is the source and { name: string } is the target. The source has the required name, but a fresh object literal also receives an excess-property check, so age can cause an error.