← TypeScript

Intermediate · 15 of 16 · 14 min read

Assignability and excess properties

The rule that decides whether one type fits where another is expected, the literal-only check layered on top, and the weak-type rule that catches the rest.

  • Structural typing

“Assignable” is the question behind every error message the compiler produces. The base rule is structural and simple: a value fits if it has everything the target needs. The complications are three deliberate exceptions on top of it.

The base rule

interface Point { x: number; y: number }

const extra = { x: 1, y: 2, colour: "red" };
const point: Point = extra;        // fine — it has everything Point needs

// const missing: Point = { x: 1 }; // Property 'y' is missing
console.log(point.x);

And because it is structural, names are irrelevant:

interface Point { x: number; y: number }
class Pixel { constructor(public x: number, public y: number) {} }

function draw(p: Point) { return p.x + p.y; }

console.log(draw(new Pixel(1, 2)));  // 3 — Pixel never mentions Point
console.log(draw({ x: 1, y: 2 }));   // 3

Exception one: fresh object literals

interface Options { timeout: number }

const fromVariable = { timeout: 1, retries: 3 };
const a: Options = fromVariable;              // fine

// const b: Options = { timeout: 1, retries: 3 };
// Object literal may only specify known properties, and 'retries' does not exist
console.log(a.timeout);

Both values are structurally identical. The literal gets an extra check because a property nobody declared, written inline, is almost always a typo — and the check only applies to a fresh literal, which is why a variable gets through.

It also fires in a function call and in a return:

interface Options { timeout: number }
function configure(options: Options) { return options.timeout; }

// configure({ timeout: 1, retries: 3 }); // caught
const opts = { timeout: 1, retries: 3 };
console.log(configure(opts));             // not caught

Four ways through it, only three of them honest:

interface Options { timeout: number }

// 1. Declare the property you want:
interface Extended extends Options { retries: number }
const a: Extended = { timeout: 1, retries: 3 };

// 2. An index signature, if extra keys are genuinely expected:
interface Loose extends Options { [key: string]: unknown }
const b: Loose = { timeout: 1, retries: 3 };

// 3. `satisfies`, which checks without widening:
const c = { timeout: 1 } satisfies Options;

// 4. `as Options` — silences the check and the typo with it. Avoid.
console.log(a.retries, b.retries, c.timeout);

Exception two: weak types

A type whose members are all optional would otherwise accept almost anything, so there is a special rule: the value must share at least one property with it.

interface Options { timeout?: number; retries?: number }

// const a: Options = { nothing: true };
// Type '{ nothing: boolean; }' has no properties in common with type 'Options'

const b: Options = {};                 // empty is fine
const c: Options = { timeout: 1 };
console.log(Object.keys(b).length, c.timeout);

It catches the obvious mistakes and not the subtle ones — a variable with one matching property and five wrong ones still passes. A required discriminant removes the ambiguity:

interface Safer { kind: "options"; timeout?: number }
const d: Safer = { kind: "options" };
console.log(d.kind);

Exception three: private members

A private or # member makes a class nominal. Two classes with identical shapes stop being interchangeable:

class A { private token = "x"; constructor(public name: string) {} }
class B { private token = "x"; constructor(public name: string) {} }

const a = new A("Ana");
// const b: B = a;
// Types have separate declarations of a private property 'token'
console.log(a.name);

The private member is identified by its declaration, not its name — so even an identical declaration in a different class does not match.

Functions

Parameters and returns go opposite ways, which is the part people have to look up:

class Animal { name = ""; }
class Dog extends Animal { bark() {} }

type DogHandler = (dog: Dog) => void;

const acceptsAnimal = (animal: Animal) => console.log(animal.name);
const acceptsDog = (dog: Dog) => dog.bark();

const a: DogHandler = acceptsAnimal;  // fine — a wider parameter is assignable
// const b: (a: Animal) => void = acceptsDog; // rejected — narrower parameter

a(new Dog());

A handler that accepts any Animal can stand in wherever a Dog handler is expected, because every Dog is an Animal. The reverse would let a Dog-only handler be called with a plain Animal.

Parameter count is checked loosely in the other direction — fewer is fine:

type Handler = (value: string, index: number) => void;

const ignoresIndex: Handler = (value) => console.log(value); // fine
// const wantsMore: Handler = (v, i, extra: boolean) => {};  // rejected

["a"].forEach((value) => console.log(value)); // why the rule exists
ignoresIndex("a", 0);
Position Rule
Object members the target’s members must all be present and compatible
Fresh object literal plus: no undeclared properties
All-optional target plus: at least one property in common
Class with private / # nominal — the same declaration or nothing
Function parameters contravariant: wider is assignable
Function parameter count fewer is assignable, more is not
Function return covariant: narrower is assignable
Method shorthand parameters bivariant, for historical compatibility
Arrays covariant, and deliberately unsound

Two deliberate unsoundnesses

Worth knowing because an interviewer may ask for an example of TypeScript being unsafe on purpose.

Arrays are covariant:

class Animal {}
class Dog extends Animal { bark() {} }

const dogs: Dog[] = [new Dog()];
const animals: Animal[] = dogs;   // allowed
animals.push(new Animal());        // and now dogs contains an Animal
// dogs[1].bark();                 // compiles, crashes

console.log(dogs.length); // 2

readonly Animal[] is the sound version when a function only reads.

Method shorthand is bivariant:

interface WithMethod { handle(value: string | number): void }
interface WithProperty { handle: (value: string | number) => void }

const narrow = (value: string) => console.log(value.length);

const a: WithMethod = { handle: narrow };    // allowed — bivariant
// const b: WithProperty = { handle: narrow }; // rejected under strictFunctionTypes
a.handle("ok");

Both exist because the sound rule broke too much real code. The property form is the safer spelling for a callback.

Reading an error message

Assignability errors nest, and the useful information is usually at the bottom:

Type '{ id: string; }' is not assignable to type 'User'.
  Types of property 'id' are incompatible.
    Type 'string' is not assignable to type 'number'.

Read it inside out: the last line is the actual mismatch, and the lines above are the path the compiler took to find it. For a deeply nested shape, that path is the fastest way to the property that is wrong.

Common mistakes

Reaching for as when a literal is rejected

Mistake. const o = { timeuot: 1 } as Options. Why it fails. The excess property check was the thing that would have caught the typo. What to do instead. Fix it, declare it, or use satisfies.

Expecting extra properties to be stripped

Mistake. Assigning a wide object to a narrow type and assuming the rest is gone. Why it fails. Nothing is removed — the type only describes a view of the value, so the extra keys are still there at runtime and in JSON.stringify. What to do instead. Build the narrow object explicitly when the payload matters.

Passing a mutable array where only reading was intended

Mistake. function count(items: Animal[]) called with a Dog[]. Why it fails. Array covariance lets it through, and the function could push a plain Animal into the caller’s array. What to do instead. readonly Animal[], which accepts the Dog[] and has no push.

Check yourself

2 questions from the bank on what you just read. Answering here does not affect your quiz history.

A class is a type like any other, and compatibility is still decided by shape.

Does this compile?

Code sample
class Person {
  constructor(public name: string) {}
}

const impostor: Person = { name: "Ana" };

An excess property check only fires on a literal written directly at the assignment.

Why does the typo survive here?

Code sample
interface Options { retries?: number }

function configure(options: Options) {}

const opts = { retires: 3 };
configure(opts);
Practise Structural typing →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.