Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 96 ยท Objects and Classes

Type Compatibility and Variance

Learn when one TypeScript type is assignable to another - structural rules, excess property checks, function parameters, covariance, contravariance and branded types.

Almost every TypeScript error you'll ever see boils down to one question: is type A assignable to type B? Passing an argument, returning a value, storing something in a variable or an array: each is an assignment, and the compiler answers that question every time. Knowing the rules it uses turns cryptic errors into obvious ones and helps you design types that catch real bugs.

This lesson explains structural assignability for objects, why object literals get an extra excess property check, how functions are compared (fewer parameters are fine, parameter types flip direction), what covariance and contravariance mean in plain words, where TypeScript is deliberately unsound, and how branded types let you opt out of structural typing when two things share a shape but must never be mixed. It builds on Object Types in Depth and Classes, Interfaces and Structural Typing.

The basic rule: at least the required members

TypeScript uses structural typing. A value of type S can be assigned to a target type T when S has every member T requires, each with a compatible type. Extra members don't hurt, and the names of the types don't matter:

TypeScript Structural assignability

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

asNamed still points at the same object, so logging it prints all four properties. The type Named only limits what you can access through that variable, not what the object contains. That's an important mental model: assigning to a wider type is like looking at the object through a smaller window.

The rule runs one way. Named isn't assignable to Employee, because a Named might lack salary. In type-system language, Employee is a subtype of Named (it has more), and Named is a supertype.

Optional properties follow the same idea. A target's optional team?: string is satisfied by an object that has no team at all, or one whose team is a string. But if the source has team: number, the types clash even though the property is optional.

Excess property checks for fresh object literals

If extras are fine, why does this fail?

TypeScript Excess property checks (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(10,24): error TS2561: Object literal may only specify known properties, but 'retires' does not exist in type 'Options'. Did you mean to write 'retries'?
main.ts(12,41): error TS2353: Object literal may only specify known properties, and 'colour' does not exist in type 'Options'.

This isn't a contradiction of the structural rule; it's an extra check on top of it. When you write an object literal directly where a type is expected, the literal is "fresh": nothing else can ever see its extra properties, so an unknown property is almost certainly a typo. TypeScript reports it, and even suggests retries. As soon as the object is stored in a variable first, it stops being fresh and only the normal assignability rule applies:

TypeScript Fresh literals versus variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The // @ts-expect-error comment tells the compiler "the next line has an error, and that's intended". The program then compiles and runs, and if the line ever stops being an error, @ts-expect-error itself becomes an error, so the demonstration can't go stale. Without the comment you'd see TS2559, Type '{ color: string; }' has no properties in common with type 'Options'. That's the weak type check: a type whose properties are all optional would otherwise accept almost anything.

Comparing functions

Functions are compared by their parameters and their return type. Two rules cover nearly everything.

Return types go the same direction. A function returning Employee can be used where a function returning Named is expected, because callers get at least what they asked for.

Fewer parameters are fine. A function that ignores some arguments can be passed where more arguments will be supplied. That's why you can pass (item) => ... to forEach even though it calls the callback with three arguments:

TypeScript Return types and parameter counts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The last part shows a related rule from Function Types and Callbacks: a function type returning void accepts functions that return anything, because the caller promises to ignore the result. push returns a number, and that's fine.

Parameter types flip direction

Parameters are where intuition breaks. Suppose you need a (e: Employee) => void handler. Is a function that accepts any Named OK? Yes: it will be called with employees, and every employee is a Named. Is a function that requires an Employee OK where a (n: Named) => void is needed? No: it might be called with a plain Named that has no salary.

So for parameters, assignability runs opposite to the parameter types. This is called contravariance, and with strictFunctionTypes (part of --strict, which our editor always uses) TypeScript enforces it:

TypeScript Contravariant parameters (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(16,7): error TS2322: Type 'EmployeeHandler' is not assignable to type 'NamedHandler'.
  Types of parameters 'e' and 'n' are incompatible.
    Property 'salary' is missing in type 'Named' but required in type 'Employee'.

Without that check, bad({ name: 'Kim' }) would crash at runtime with Cannot read properties of undefined (reading 'toFixed').

Covariance and contravariance in one picture

These words describe how a container type behaves when you change the type inside it. Take Employee, a subtype of Named:

Position of T Example Employee version assignable to Named version? Name
Output (read) () => T, readonly T[] Yes Covariant
Input (write) (x: T) => void No, the other way round Contravariant
Both { value: T } (mutable), T[] Should be neither Invariant (in theory)

A type that you only read from is safe to widen. A type you only write to is safe to narrow. A type you both read and write should accept neither direction. TypeScript follows the first two rows strictly, but it makes a pragmatic exception for the third.

Where TypeScript is unsound on purpose

Mutable arrays and object properties are treated as covariant, even though writing through them can break the rules. This keeps everyday code easy (you can pass a Dog[] to a function that takes Animal[]), but it means the compiler can miss a bug like this:

TypeScript Array covariance lets a bug through

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program compiles, then prints Rex Woof! and Tom: dog.bark is not a function. Nothing in the types warned you. The defense is to say what you mean: a parameter typed readonly Animal[] can't be pushed to, so accepting Dog[] there is truly safe. Readonly and Immutability builds on this.

Methods are bivariant

The second exception concerns method syntax. strictFunctionTypes only applies to properties written as function types (handle: (x: T) => void). Members written with method shorthand (handle(x: T): void) are compared bivariantly: either direction is accepted. This exists because many built-in types, including Array's own methods, would otherwise become incompatible.

TypeScript Method shorthand versus function properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The method version compiles and prints Kim no salary!. If you want the stricter check in your own interfaces, write callbacks as function-typed properties. (typescript-eslint has a rule, method-signature-style, that enforces this.)

Branded types: opting out of structure

Sometimes structural typing is too generous. A UserId and an OrderId are both numbers, a price in euros and one in dollars are both numbers, and a validated email is still a string. If they're all plain number or string, nothing stops you from mixing them up.

A branded type adds a fake, compile-time-only property that no ordinary value has. The only way to get a branded value is through a function you control, which is also the natural place to validate:

TypeScript Branded IDs and validated strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

declare const brand: unique symbol creates a symbol type without any runtime value, so the brand property can never collide with a real one and costs nothing at runtime. A branded number still works with arithmetic, because it's a number with an extra (imaginary) property: order + 1 prints 1043. The as casts are confined to the small constructor functions, which is exactly where you want unsafe code to live.

Branded types are the lightweight sibling of the class trick from the previous lesson (a private member makes a class nominal). Use brands for primitives such as IDs, units and validated strings; use classes when the value also needs behavior. Advanced Type-Level Programming shows more brand patterns.

A quick reference

Situation Rule
Object to object Source needs every required target member, with compatible types; extras are fine
Fresh object literal Also rejects unknown properties (TS2353, TS2561)
All-optional ("weak") target Source must share at least one property (TS2559)
Function return types Covariant: a more specific return type is fine
Function parameter count Fewer parameters are fine
Function parameter types Contravariant under strictFunctionTypes; bivariant for method shorthand
Mutable arrays and properties Treated as covariant (convenient but unsound)
private/protected/#private Only the declaring class and its subclasses are compatible
any Assignable to and from everything (avoid it)
unknown / never Everything goes into unknown; never goes into everything

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given interface P { x: number }, which line compiles?

    Storing the object in a variable first means it is no longer a fresh literal, so only the structural rule applies and the extra y is fine. The first line fails the excess property check; the third lacks x.
  2. 2. With strictFunctionTypes, is (n: Named) => void assignable to (e: Employee) => void, where Employee extends Named?

    Parameters are contravariant. A function that accepts the wider type Named works wherever a function accepting Employee is needed.
  3. 3. A function takes animals: Animal[] and pushes a Cat. You call it with a Dog[]. What happens?

    TypeScript treats mutable arrays as covariant for convenience, which is unsound. Use readonly Animal[] for functions that only read.
  4. 4. What does type UserId = number & { readonly [brand]: 'UserId' } add at runtime?

    Brands are compile-time fiction. The value stays a plain number; only the constructor function's cast creates the branded type.
  5. 5. Why does start({ verbose: true, retires: 3 }) fail when start takes { verbose?: boolean; retries?: number }?

    The excess property check only applies to fresh object literals, where an unknown property is almost always a mistake. TypeScript even suggests retries.

Summary

  • Assignability is structural: the source needs every required member of the target with compatible types; extras are allowed, and type names don't matter.
  • Fresh object literals also get an excess property check, and all-optional "weak" types require at least one shared property.
  • Functions: return types are covariant, fewer parameters are fine, and parameter types are contravariant under strictFunctionTypes.
  • Method shorthand members are compared bivariantly, and mutable arrays are treated as covariant. Both are deliberate holes; use function-typed properties and readonly arrays to close them.
  • Branded types (T & { readonly [brand]: 'Name' }) make structurally identical values incompatible at zero runtime cost; create them in small validating functions.

Next: Readonly and Immutability