Sub topic 4
The idea behind most errors: assignability
This chapter assumes you can run tsc, read a one-line diagnostic with its file, position, and code, and write interfaces, type aliases, and union types. It builds the model that explains most of the messages you will see later.
One question behind many errors
Most TypeScript errors come from one question: can a value of type S be used where type T is expected? S is the source and T is the target. If the answer is yes, S is assignable to T. If not, the compiler reports an error.
The question is asked in three places:
- Assignment and initialization:
const x: T = valueOfS. - Calls: passing an argument of type S to a parameter of type T.
- Returns: returning a value of type S from a function declared to return T.
The wording of the message names both sides. In Type 'string' is not assignable to type 'number', the first type is the source and the second is the target. When you read a diagnostic, find the source and target first. Everything else in the message explains why the check failed.
Assignability is structural
TypeScript compares shapes, not names. A type is assignable to another if it has at least the members the target requires, with compatible types.
interface Point {
x: number;
y: number;
}
const labeled = { x: 1, y: 2, label: "origin" };
const p: Point = labeled; // OK: has x and y, extra members are allowed
console.log(p.x, p.y);labeled was never declared as a Point. It has x: number and y: number, so it fits. Extra members do not break assignability. This is why two unrelated interfaces with the same fields are interchangeable.
The excess property check
There is one exception. When you write an object literal directly in an assignment or call, TypeScript also rejects properties the target does not know about. This catches typos.
interface Point {
x: number;
y: number;
}
const q: Point = { x: 1, y: 2, z: 3 };This reports TS2353: Object literal may only specify known properties, and 'z' does not exist in type 'Point'. The same members pass when they arrive through a variable, as the previous example showed. Only fresh object literals get the stricter check.
Unions: every member must fit
A source union is assignable only if every member of the union is assignable to the target. A source can also go into a target union if it fits at least one member.
function show(value: string | number): void {
const text: string = value;
console.log(text);
}The error is a two-line chain:
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.The first line is the claim. The second line names the union member that failed. The reverse direction works, because a string fits into string | number.
| Source | Target | Assignable? | Reason | Column |
|---|---|---|---|---|
| `string` | `string \ | number` | Yes | Fits one member |
| `string \ | number` | `string` | No | `number` does not fit |
| `"fast"` | `"fast" \ | "safe"` | Yes | Fits one member |
| `{ x: number; y: number; z: number }` | `{ x: number; y: number }` | Yes | Has all required members | |
| `{ x: number }` | `{ x: number; y: number }` | No | Missing `y` |
Literal types and widening
A literal type such as "fast" is assignable to string. The reverse is not true. This matters because TypeScript sometimes widens a literal to its general type when it infers a type for a mutable location.
type Mode = "fast" | "safe";
const a: Mode = "fast"; // OK: the literal fits
let b = "fast"; // inferred as string, because let can be reassigned
const c: Mode = b; // errorThe last line reports Type 'string' is not assignable to type 'Mode'. The value in b happens to be "fast", but the compiler checks the declared type of b, which is string. A const declaration keeps the literal type, so const b = "fast" would work.
The same widening happens to properties inside object literals, even when the object is const. That is why an object built in one place can fail to match a literal-typed parameter somewhere else. Annotating the variable with the intended type, or using as const, keeps the literals narrow.
Optional, readonly, and special types
Optional properties affect the direction of assignability:
interface Required { id: number; name: string }
interface Loose { id: number; name?: string }
declare const loose: Loose;
declare const strict: Required;
const ok: Loose = strict; // OK
const bad: Required = loose; // errorThe error says Property 'name' is optional in type 'Loose' but required in type 'Required'. A value that might lack name cannot be used where name is required.
readonly is not checked by assignability. A { readonly id: number } can be assigned to { id: number }, and the compiler will not stop you. Treat readonly as a guard on the property's own declaration, not as part of type compatibility.
Four special types behave differently from the rest:
| Type | As a source | As a target |
|---|---|---|
| `any` | Assignable to nearly everything | Accepts everything |
| `unknown` | Assignable only to `unknown` and `any` | Accepts everything |
| `never` | Assignable to everything | Accepts only `never` |
| `null`, `undefined` | Assignable to other types only when `strictNullChecks` is off | Accepted by a type only if it includes them |
any switches the check off, so errors disappear without being fixed. unknown is the safe alternative: you must narrow it before use.
Function types: parameters go the other way
Function assignability has two rules that surprise people.
First, a function with fewer parameters can stand in for one with more, because callers can ignore extra arguments. The reverse fails.
type Handler = (event: string) => void;
const fewer: Handler = () => {}; // OK
const more: Handler = (event: string, extra: number) => {}; // errorThe error ends with Target signature provides too few arguments. Expected 2 or more, but got 1.
Second, with strictFunctionTypes on (part of strict), parameters are compared in reverse. A function that accepts a wider type can replace one that accepts a narrower type, but not the other way around.
type Animal = { name: string };
type Dog = { name: string; bark(): void };
let feedDog: (d: Dog) => void = (d) => d.bark();
let feedAnimal: (a: Animal) => void = (a) => console.log(a.name);
feedDog = feedAnimal; // OK: feedAnimal handles any Dog, since a Dog is an Animal
feedAnimal = feedDog; // errorThe error chain reads:
Type '(d: Dog) => void' is not assignable to type '(a: Animal) => void'.
Types of parameters 'd' and 'a' are incompatible.
Property 'bark' is missing in type 'Animal' but required in type 'Dog'.A caller of feedAnimal may pass any Animal, and feedDog would then call bark on something that has none.
Putting the check together
The compiler works through the target's requirements and stops at the first failure. The message chain records the path to that failure.
Use this routine when an error confuses you:
- Identify the source and the target from the first line.
- Read to the last line of the chain. That line names the member or property that failed.
- Decide which side is wrong. Sometimes the value is wrong, and sometimes the annotation is too narrow or too wide.
Practice
Consider this code:
type Shape = { kind: "circle"; radius: number };
const shape = { kind: "circle", radius: 2 };
const s: Shape = shape;Exercise
The last line fails. Name the source type, the target type, the reason the check fails, and one fix that does not use an assertion.
Show answer
The source is { kind: string; radius: number }, because the object literal widened "circle" to string. The target is Shape, whose kind must be the literal "circle". string is not assignable to "circle". Fix it by annotating the variable (const shape: Shape = { kind: "circle", radius: 2 }) or by writing the literal with as const so the literal type is kept.
Exercise
A function expects a callback of type (item: string) => void. Which of these can you pass: () => {}, (item: string, index: number) => {}, or (item: string | number) => {}? Explain each.
Show answer
The first works, because a function with fewer parameters can ignore the arguments. The second fails, because the callback requires an index argument that the caller never supplies. The third works under strictFunctionTypes, because it accepts a wider parameter type, and every string is also a string | number.