Sub topic 2
Assignability: does the shape fit?
This chapter assumes you can read TypeScript type annotations, interfaces and type aliases. It also assumes you know how JavaScript objects and functions behave. The previous chapter covered what "structural" means. This chapter covers the question TypeScript asks over and over: can this value be used here?
The question behind most type errors
Most type errors come from one check. TypeScript takes the type of a value, called the source, and the type expected at that position, called the target. It then asks whether the source is assignable to the target.
That check runs in many places:
- Initializing or assigning a variable:
const t: Target = source. - Passing an argument to a function parameter.
- Returning a value from a function with a declared return type.
- Checking a type against a generic constraint, such as
T extends Target.
Assignability is a relation between two types. It does not look at names, and it does not look at how the types were declared. It looks at what each type contains.
The core rule for objects
An object source type is assignable to an object target type when, for every property in the target, the source has a property of that name whose type is assignable to the target property's type.
Two consequences follow:
- The source may have properties the target does not mention. They are ignored.
- The source must not lack any property the target requires.
interface Named {
name: string;
}
interface Person {
name: string;
age: number;
}
const person: Person = { name: "Ada", age: 36 };
const named: Named = person; // OK: Person has everything Named requires
const back: Person = named;
// Error: Property 'age' is missing in type 'Named' but required in type 'Person'.The relation is directional. Person fits where Named is expected, but Named does not fit where Person is expected. A type with more members is generally usable in more places, because it promises more.
Names play no part
The checker never asks which interface or alias a type came from. Two declarations with different names and the same members are interchangeable.
interface Meters {
value: number;
}
type Feet = {
value: number;
};
const length: Meters = { value: 3 };
const other: Feet = length; // OK: same members, different names
console.log(other.value);This is why a Meters can silently be used as Feet. A later chapter shows how to prevent that with branding. For now, treat it as the default behavior.
Recursing into property types
"Assignable property type" is the same question asked again on the property's type. The check recurses as deep as the types go.
interface Address {
city: string;
zip: string;
}
interface Customer {
name: string;
address: Address;
}
interface Contact {
name: string;
address: { city: string };
}
declare const customer: Customer;
const contact: Contact = customer; // OK: Address is assignable to { city: string }
declare const contactFromForm: Contact;
const full: Customer = contactFromForm;
// Error: Property 'zip' is missing in type '{ city: string; }'
// but required in type 'Address'.When you read an error like this, start at the innermost line. The outer lines say where the mismatch was found. The innermost line says what is actually wrong.
The optional-property branch is covered in its own chapter. The diagram shows it so the full flow is visible.
Primitives and literal types
For primitive types the same relation applies, and it is again directional. A literal type such as "open" is assignable to string. A plain string is not assignable to "open".
type Status = "open" | "closed";
const s1: Status = "open";
let text: string = s1; // OK: "open" is a string
let s2: Status = text;
// Error: Type 'string' is not assignable to type 'Status'.The pattern matches objects: the narrower type fits where the wider one is expected, and not the reverse. "open" carries more information than string.
Unions on either side
Unions follow two rules:
- A union source is assignable only if every member is assignable to the target.
- A union target accepts a source if the source is assignable to at least one member.
function demo(a: string | number) {
const wide: string | number | boolean = a; // OK: both string and number fit
const narrow: string = a;
// Error: Type 'string | number' is not assignable to type 'string'.
// Type 'number' is not assignable to type 'string'.
}The error names the failing member, number. That is the member to fix or to narrow away with a check such as typeof a === "string".
The special types
Four types sit outside the ordinary rules.
| Type | As a source | As a target |
|---|---|---|
| `any` | Assignable to almost everything (not to `never`) | Accepts anything |
| `unknown` | Assignable only to `unknown` and `any` | Accepts anything |
| `never` | Assignable to everything | Accepts only `never` |
| `object`, `{}` | Accepts any non-null value (and `object` rules out primitives) | See below |
function special(a: any, u: unknown, n: never) {
const x: number = a; // OK: any switches the check off
const y: number = u;
// Error: Type 'unknown' is not assignable to type 'number'.
const z: number = n; // OK: never has no values, so nothing can go wrong
const w: unknown = 42; // OK: every value is assignable to unknown
}any is the one to be careful with. It does not take part in the shape comparison at all, so an any value can flow into a strict type without any error. Prefer unknown when you do not know a value's type. It forces a check before use.
The target {} is worth a note. It means "any value except null and undefined", which includes numbers and strings. A target of {} does not mean "an empty object". It has no required properties, so almost any source satisfies it.
Assignable is not the same as identical
Two types can be mutually assignable and still be different declarations. They can also be one-way assignable, as Person and Named were above. The checker treats identity as a special case of assignability. It does not use identity as its main test.
The relation also underlies generic constraints. When you write T extends { id: number }, the check on each call is the same assignability question.
function getId<T extends { id: number }>(item: T): number {
return item.id;
}
const item = { id: 1, label: "first" };
console.log(getId(item)); // OK: the inferred T has id: number
getId({ label: "x" });
// Error: Argument of type '{ label: string; }' is not assignable to
// parameter of type '{ id: number; }'.The first call passes because T is inferred as { id: number; label: string }, which has the required id. The second call fails because the source lacks id.
What assignability does not do
Assignability is a compile-time judgment about types. It does not change values.
interface Point {
x: number;
y: number;
}
const p3 = { x: 1, y: 2, z: 3 };
const p: Point = p3; // OK
console.log(JSON.stringify(p)); // {"x":1,"y":2,"z":3}
console.log(p.z);
// Error: Property 'z' does not exist on type 'Point'.Annotating p as Point limits what you may access through p. The object itself still has z at runtime. The type says "at least x and y". It does not say "only x and y".
This gap between the declared type and the real value is the source of several pitfalls. A later chapter covers Object.keys as one of them.
Common mistakes
- Reading assignable as "equal". If
Ais assignable toB,Bis not necessarily assignable toA. Check both directions when you need to know. - Expecting extra properties to be rejected everywhere. Extra properties are fine in the general case. The next chapters cover the specific cases where TypeScript does complain about them.
- Trusting
any. Ananyvalue hides mismatches. The error appears later, at runtime. - Assuming a type guarantees a value's contents. Types describe a minimum. Data parsed from JSON or received over a network can have a different shape at runtime than its declared type.
Exercise
Given interface A { id: number } and interface B { id: number; tags: string[] }, which of const x: A = bValue and const y: B = aValue compiles, and why? Assume bValue has type B and aValue has type A.
Show answer
Only const x: A = bValue compiles. B has every property A requires (id: number), and its extra property tags is ignored. A lacks tags, which B requires, so const y: B = aValue fails with "Property 'tags' is missing in type 'A' but required in type 'B'".
Exercise
In the function below, why does the second assignment fail while the first succeeds? What is the smallest change that makes the second one compile? function f(v: string | number) { const a: string | number | null = v; const b: string = v; }
Show answer
A union source is assignable only if every member is assignable to the target. string | number fits in string | number | null because both members appear in the target union. It does not fit in string because number is not assignable to string. Narrowing v first fixes it, for example if (typeof v === "string") { const b: string = v; }.