Sub topic 18
Where assignability is intentionally unsound
This chapter assumes you have read the earlier chapters on structural typing, variance, and strictFunctionTypes. A type system is sound if a program that passes the checker can never hold a value whose runtime type differs from its static type. TypeScript does not aim for that. Its design goals list "apply a sound or provably correct type system" as a non-goal and ask for a balance between correctness and productivity. This chapter covers the main places where the assignability rules accept code that can fail at runtime, and why each one is allowed.
Array covariance
Arrays are treated as covariant in their element type. A Dog[] is assignable to Animal[], even though Animal[] allows writes that Dog[] does not.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
const dogs: Dog[] = [{ name: "Rex", bark() { console.log("woof"); } }];
const animals: Animal[] = dogs; // OK: arrays are treated as covariant
animals.push({ name: "cat" }); // compiles, but dogs now holds a non-Dog
dogs[1].bark(); // compiles, throws TypeError at runtimeA sound checker would make arrays invariant. Then a function taking Animal[] and only reading from it would reject a Dog[], and that function is the most common kind. TypeScript chose convenience, because most code reads from arrays far more often than it writes through a wider alias.
Method bivariance
Under strictFunctionTypes, function-typed properties check parameters contravariantly. Members declared with method syntax are exempt and stay bivariant. A method parameter can therefore be either a subtype or a supertype of the target's parameter.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
interface MethodStyle { handle(a: Animal): void }
interface PropertyStyle { handle: (a: Animal) => void }
const impl = { handle(d: Dog) { d.bark(); } };
const m: MethodStyle = impl; // OK: method parameters stay bivariant
const p: PropertyStyle = impl; // Error under strictFunctionTypes
m.handle({ name: "cat" }); // compiles, throws TypeError: d.bark is not a functionThe exemption exists so that built-in types keep working. If Array<T> were checked strictly, Array<Dog> would not be assignable to Array<Animal>, because methods such as push(...items: T[]) take T in a contravariant position. Declaring those members with method syntax keeps array covariance working. The cost is that every method you declare gets the same laxness. If you want strict checking for a callback, declare it as a property with a function type.
Readonly is not tracked across assignments
readonly blocks writes through the annotated name. It does not make the value immutable, and it does not change assignability between object types.
interface ReadonlyPoint { readonly x: number }
interface MutablePoint { x: number }
const ro: ReadonlyPoint = { x: 1 };
const mut: MutablePoint = ro; // OK: readonly does not affect assignability
mut.x = 2; // ro.x is now 2 as wellWritable and readonly properties are mutually assignable. Arrays differ here. readonly string[] is not assignable to string[], because the readonly array type lacks push and similar members. That difference comes from missing methods, not from a rule about readonly itself.
Mutable properties are covariant
The same reasoning applies to ordinary object properties. A property is a read and a write, but the checker compares property types only in the read direction.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
declare const dogBox: { pet: Dog };
const animalBox: { pet: Animal } = dogBox; // OK
animalBox.pet = { name: "cat" }; // compiles, dogBox.pet is no longer a DogMaking properties invariant would reject large amounts of ordinary code, such as passing a { pet: Dog } to a function that only reads pet.name.
Return type `void`
A function type whose return type is void accepts functions that return anything. The return value is ignored.
const cb: () => void = () => 42; // OK: the result is discarded by callers
const numbers = [1, 2, 3];
const out: number[] = [];
numbers.forEach((n) => out.push(n)); // push returns a number, forEach expects voidThis is intentional. Without it, you could not pass out.push or a concise arrow function to forEach. The related risk is that a caller who expects void cannot use the result. The declared type says void, so the checker will not let you rely on the real value.
Index access and missing elements
Indexing an array or an index-signature type returns the element type, with no undefined added.
const names: string[] = ["Ada"];
const third: string = names[2]; // OK: type is string, value is undefined
console.log(third.toUpperCase()); // compiles, throws TypeErrorThe noUncheckedIndexedAccess compiler option adds undefined to these reads. It is off by default, and it is not part of strict, so you must turn it on yourself.
Escape hatches
Some features are unsound by design because they let you override the checker.
anyis assignable to and from nearly everything (exceptnever), so it switches checking off for any value that touches it.- Type assertions (
x as T) are allowed when the two types are comparable, a looser relation than assignability. Comparability accepts a cast fromAnimaltoDogeven though anAnimalis not assignable toDog. The checker rejects only casts between types with no overlap, such asstringtonumber. - The non-null assertion
x!removesnullandundefinedfrom a type without any runtime check. - A function declared with a type predicate (
x is T) is trusted. The checker does not verify that the body does what the predicate claims.
Summary of the unsound cases
| Case | Compiles | Fails at runtime when | Stricter alternative |
|---|---|---|---|
| Array covariance | `Animal[] = Dog[]` | You write a non-`Dog` through the alias | `readonly Animal[]` for read-only parameters |
| Method bivariance | `handle(d: Dog)` as `handle(a: Animal)` | A caller passes a non-`Dog` | Declare as `handle: (a: Animal) => void` |
| Readonly mismatch | `readonly x` to `x` | The mutable alias writes | Avoid sharing mutable aliases |
| Unchecked index | `names[2]` typed `string` | The index is out of range | `noUncheckedIndexedAccess` |
Decision criteria
Treat these cases as known risks and reduce them where the cost is low. Use property syntax for callback members when you need contravariance. Use readonly arrays on read-only parameters. Turn on noUncheckedIndexedAccess if your code indexes often. Validate external data at the boundary instead of asserting its type. Accept the remaining gaps in exchange for code that checks cleanly in the common case.
Exercise
Why does const animals: Animal[] = dogs; compile, and what single change to the type of animals makes a following animals.push({ name: "cat" }) fail to compile?
Show answer
TypeScript treats arrays as covariant in their element type, so Dog[] is assignable to Animal[] even though the target allows writes of non-Dog values. Changing the annotation to readonly Animal[] removes push, so the call is a compile error, and the assignment from Dog[] still compiles.
Exercise
An interface declares onChange(value: Animal): void. An object whose onChange takes a Dog is assigned to it without error. How do you rewrite the interface so that this assignment is rejected under strictFunctionTypes?
Show answer
Declare the member as a function-typed property: onChange: (value: Animal) => void. Property-style function types are checked contravariantly under strictFunctionTypes, so a handler that requires a Dog is no longer assignable. Method syntax stays bivariant.