Sub topic 1
How TypeScript compares shapes: structural typing
This chapter explains the rule TypeScript uses to decide whether one value can be used where another type is expected. Every later chapter on interfaces and type aliases builds on this rule.
Prerequisites
This chapter assumes you already know the following:
- Basic TypeScript type annotations (
string,number,boolean, arrays). - JavaScript objects, functions, and classes.
- How to run the TypeScript compiler (
tsc) or use an editor that shows type errors.
You do not need to know interfaces or type aliases yet. This chapter uses a small amount of interface syntax and explains it as it appears.
Learning goals
After this chapter you will be able to:
- State the rule TypeScript uses to decide whether a value matches a type.
- Predict when a value with extra properties is accepted and when it is rejected.
- Explain why the declared name of a type rarely matters.
- Recognize the common errors that come from this rule.
Two ways to compare types
Languages compare types in one of two ways.
- Nominal typing compares names. Two types are compatible only if they are declared as related. Java and C# work this way for classes.
- Structural typing compares shape. Two types are compatible if one has all the members the other requires, with compatible types. The declared names do not matter.
TypeScript is structural. This fits JavaScript, where objects are usually built as plain literals and passed around without any class declaration.
The rule, stated simply: a value of type S can be used where type T is expected if S has at least every property that T requires, and each of those properties has a type that is assignable to the matching property in T. We say S is assignable to T.
A first example
interface Point {
x: number;
y: number;
}
function length(p: Point): number {
return Math.sqrt(p.x * p.x + p.y * p.y);
}
const origin3d = { x: 3, y: 4, z: 5 };
console.log(length(origin3d)); // 5, because origin3d has every property Point requiresorigin3d was never declared as a Point. It has no connection to the Point name. The compiler inspects its inferred type, { x: number; y: number; z: number }, and finds x and y with the right types. The extra property z does not matter, so the call is accepted.
Think of Point as a checklist. A value passes if it satisfies every item. Having more than the checklist asks for is fine.
What the compiler checks
For each property in the target type, the compiler asks two questions about the source.
- Does the property exist?
- Is its type assignable to the target's property type?
If a required property is missing, you get an error:
interface Point {
x: number;
y: number;
}
const flat = { x: 3 };
const p: Point = flat;
// Error: Property 'y' is missing in type '{ x: number; }' but required in type 'Point'.If a property has the wrong type, you also get an error:
interface Point {
x: number;
y: number;
}
const wrong = { x: 3, y: "4" };
const q: Point = wrong;
// Error: Type 'string' is not assignable to type 'number'.The check is recursive. If a property is itself an object type, the same comparison runs on that nested type.
interface Line {
start: { x: number; y: number };
end: { x: number; y: number };
}
const segment = {
start: { x: 0, y: 0, label: "A" },
end: { x: 5, y: 5, label: "B" },
};
const line: Line = segment; // allowed: each nested object has x and yNames do not matter
Two differently named types with the same shape are interchangeable.
interface Meters {
value: number;
}
interface Seconds {
value: number;
}
const distance: Meters = { value: 100 };
const duration: Seconds = distance; // allowed, even though the names differThis is the main surprise for developers coming from Java or C#. TypeScript will not stop you from passing a Meters where Seconds is expected, because both are just { value: number }. The same holds between an interface and a type alias with the same shape. Later chapters show that the choice between the two constructs rarely changes what the compiler accepts, since both describe shapes.
If you need to keep such types apart, you must make their shapes different, for example by adding a distinguishing property. That technique, often called branding, is outside this chapter.
Excess property checks
There is one place where TypeScript seems to break the "extra properties are fine" rule. Compare these two cases.
interface Point {
x: number;
y: number;
}
const a: Point = { x: 1, y: 2, z: 3 };
// Error: Object literal may only specify known properties, and 'z' does not exist in type 'Point'.
const temp = { x: 1, y: 2, z: 3 };
const b: Point = temp; // allowedThe first assignment fails and the second succeeds, though the value is the same. The difference is that the first uses a fresh object literal: an object literal written directly where a typed value is expected. For fresh literals, TypeScript adds an excess property check. An extra property in a literal you just wrote is most likely a typo, so the compiler flags it.
Once the object is stored in a variable, it is no longer fresh, and the check no longer applies. The structural rule is the same in both cases. The excess property check is an extra safety net on top of it.
Excess property checks also catch misspelled optional properties:
interface Options {
timeout?: number;
}
const opts: Options = { timeot: 1000 };
// Error: Object literal may only specify known properties, but 'timeot' does not exist in type 'Options'.Without the check, this literal would be accepted, because every property of Options is optional and the empty requirement is trivially met.
Assignability is directional
Assignability goes one way. A value with more properties can be used where fewer are required, but not the reverse.
interface Named {
name: string;
}
interface Person {
name: string;
age: number;
}
const person: Person = { name: "Ada", age: 36 };
const named: Named = person; // allowed: Person has everything Named requires
const other: Named = { name: "Grace" };
// const backToPerson: Person = other; // error: Property 'age' is missing in type 'Named' but required in type 'Person'.The type with more requirements is the more specific type. A more specific value can stand in for a more general one. Many TypeScript errors come from trying the opposite direction.
Functions and structural compatibility
The same idea applies to function parameters. A function that needs only a Named will accept anything with a name:
interface Named {
name: string;
}
function greet(who: Named): string {
return "Hello, " + who.name;
}
const employee = { name: "Grace", employeeId: 7 };
console.log(greet(employee)); // Hello, GraceThis is a practical design guideline. Declare parameters with the smallest shape the function actually uses. Callers can then pass many kinds of values without conversion, and the signature documents which properties the function reads.
Classes are compared structurally too
Classes do not escape the rule. Two unrelated classes with the same public members are interchangeable.
class Dog {
name = "Rex";
}
class Cat {
name = "Tom";
}
const pet: Dog = new Cat(); // allowed: Cat has everything Dog requiresThere is one exception. If a class has private or protected members, the compiler requires that those members originate in the same declaration. Two separate classes with a private member of the same name are then not compatible. This is the only place where TypeScript behaves somewhat nominally.
Common errors and how to read them
| Situation | Typical message | What it means |
|---|---|---|
| A required property is absent | Property 'y' is missing in type ... | The source shape lacks something the target needs. |
| A property has an incompatible type | Type 'string' is not assignable to type 'number' | A property exists but its type does not fit. |
| An extra key in a fresh literal | Object literal may only specify known properties | The excess property check found a likely typo. |
| Passing a general type where a specific one is needed | Property 'age' is missing in type 'Named' | Assignability goes from specific to general only. |
When an error message is long, read the last lines first. The compiler usually ends with the specific property that failed, after listing the enclosing types.
Why this design helps and where it bites
Structural typing has clear benefits.
- You can describe the shape you need without forcing callers to import or inherit from a particular declaration.
- Test doubles and plain objects work wherever a matching shape is expected.
- Code from separate libraries interoperates when their shapes agree.
It also has costs.
- Types with the same shape but different meaning, such as
MetersandSeconds, are not kept apart. - A function accepting a wide object type may receive values with unexpected extra data. Do not iterate over all of an object's keys and assume you only see the declared ones.
- Excess property checks apply only to fresh literals, so they can give a false sense of strictness.
Summary
TypeScript decides compatibility by comparing shapes. A source is assignable to a target when it has every required property with a compatible type, and extra properties are allowed. Names do not matter, with a narrow exception for classes with private or protected members. Fresh object literals get an additional excess property check. The rest of this tutorial describes the tools, interfaces and type aliases, that you use to write these shapes down.
Exercise
Given interface Point { x: number; y: number }, explain why const a: Point = { x: 1, y: 2, z: 3 }; is an error while const t = { x: 1, y: 2, z: 3 }; const b: Point = t; is accepted.
Show answer
Both values have all the properties Point requires, so both satisfy the structural rule. The first is a fresh object literal, so TypeScript also runs the excess property check and rejects the unknown property z. In the second, t is a variable and no longer fresh, so only the structural check runs, and extra properties are allowed.
Exercise
Two interfaces are declared as interface Meters { value: number } and interface Seconds { value: number }. Does TypeScript allow const s: Seconds = meters; when meters has type Meters? Why?
Show answer
Yes. TypeScript compares shapes, not names. Both types are { value: number }, so a Meters value is assignable to Seconds.
Exercise
Given interface Named { name: string } and interface Person { name: string; age: number }, which assignment is an error: a Person value to a Named variable, or a Named value to a Person variable? Explain.
Show answer
Assigning a Named value to a Person variable is an error. Named lacks the required property age. A Person has everything Named requires, so that direction is allowed.