Sub topic 3
Object shapes and extra properties
This chapter assumes you know basic TypeScript syntax (type annotations, interfaces, type aliases) and how JavaScript objects, classes and functions work. It covers the rule TypeScript uses to compare object types, and why a value with more properties than required still fits.
What a shape is
The shape of an object type is the set of its members. Each member has a name, a type, and flags such as optional or readonly. Methods are members too. TypeScript never asks which interface or class produced a value. It asks whether the value has the members the target type needs.
interface Point {
x: number;
y: number;
}
function logPoint(p: Point) {
console.log(`${p.x}, ${p.y}`);
}
const p3 = { x: 1, y: 2, z: 3 };
logPoint(p3); // OK: p3 has at least x and y
class Vec {
constructor(public x: number, public y: number) {}
}
logPoint(new Vec(1, 2)); // OK: Vec never declares that it implements Pointp3 has an inferred type that no one named. Vec is a class that has never heard of Point. Both are accepted because both contain x: number and y: number.
The comparison rule
When TypeScript checks whether a source type S can be used where a target type T is expected, it walks through the members of T. For each one it asks two questions:
- Does
Shave a member with that name? - Is the type of that member in
Sassignable to the type of the member inT?
If every member of T passes, S is assignable to T. Members of S that T does not mention are never examined. The check is directional. It is driven by the target, and the source can be larger.
Extra properties are allowed
A source with more members than the target is accepted. This follows from how the relationship is defined. A type with more members describes a smaller set of values, because each added requirement rules some values out. Every value that has x, y and z also has x and y, so using a three-property value where a two-property value is expected is safe.
This is why a function can accept a small interface and be called with many different objects:
interface HasId {
id: number;
}
function describe(item: HasId): string {
return `item #${item.id}`;
}
const user = { id: 1, name: "Ada" };
const order = { id: 42, total: 99.5, items: ["pen", "ink"] };
console.log(describe(user)); // item #1
console.log(describe(order)); // item #42The function body can only read id. The type HasId says nothing about the other properties, so TypeScript will not let describe touch them. At runtime they still exist, and that matters later in this chapter.
Missing members
Because the target drives the check, a source that lacks a required member fails:
interface Point {
x: number;
y: number;
}
declare function logPoint(p: Point): void;
const partial = { x: 1 };
logPoint(partial);
// Error: Property 'y' is missing in type '{ x: number; }'
// but required in type 'Point'.The error names the missing member and both types. Read it from the target's point of view: Point requires y, and partial does not supply it.
Mismatched member types
Presence is not enough. The member's type must also fit.
interface Point {
x: number;
y: number;
}
declare function logPoint(p: Point): void;
const bad = { x: 1, y: "2" };
logPoint(bad);
// Error: Argument of type '{ x: number; y: string; }' is not
// assignable to parameter of type 'Point'.
// Types of property 'y' are incompatible.
// Type 'string' is not assignable to type 'number'.For properties, the source type must be assignable to the target type. A narrower property type can stand in for a wider one:
interface Wide {
id: string | number;
}
const narrow: { id: string } = { id: "a" };
const w: Wide = narrow; // OK: string is assignable to string | number
const wide2: Wide = { id: 1 };
const n: { id: string } = wide2;
// Error: Type 'string | number' is not assignable to type 'string'.The first assignment is safe for reading, since every id is a string and so also a string | number. TypeScript applies the same rule to properties you write to, which is slightly unsound. You could write a number through Wide into an object that is still typed as { id: string } elsewhere. TypeScript accepts this trade-off for convenience.
Nested shapes are compared recursively
When a member is itself an object type, the same rule applies one level down:
interface Address {
city: string;
}
interface Person {
name: string;
address: Address;
}
const home = { city: "Oslo", zip: "0150" };
const person: Person = { name: "Ada", address: home }; // OKhome has an extra zip, which is fine for the same reason as before. The checker compares { city: string; zip: string } to Address, finds city, and ignores zip. Writing the object inline, with address: { city: "Oslo", zip: "0150" } directly inside the literal, behaves differently, and the next chapter explains why.
Methods and call members
Methods are members like any other. A source needs a member of the same name whose function type is assignable to the target's method type.
interface Greeter {
name: string;
greet(): string;
}
const english = {
name: "en",
greet() {
return "hello";
},
volume: 11,
};
const g: Greeter = english; // OK
const silent = { name: "none" };
const g2: Greeter = silent;
// Error: Property 'greet' is missing in type '{ name: string; }'
// but required in type 'Greeter'.How function types compare to each other, including parameters and return types, has its own chapter.
Where the name of a type matters
Names have almost no effect on assignability between plain object types, with two exceptions that later chapters cover:
- Classes with
privateorprotectedmembers. These must come from the same declaration, so such classes behave nominally. - Branded types, where you add a phantom property on purpose to make otherwise identical shapes incompatible.
Everything else is shape only. Two interfaces with the same members are interchangeable. An interface and a type alias with the same members are interchangeable too.
| Source | Target | Assignable? | Reason |
|---|---|---|---|
| `{ x: number; y: number; z: number }` | `Point` | Yes | Has all required members; `z` is ignored |
| `{ x: number }` | `Point` | No | `y` is missing |
| `{ x: number; y: string }` | `Point` | No | `y` has an incompatible type |
| `Vec` (class with public `x`, `y`) | `Point` | Yes | Only the shape matters |
| `Point` | `{ x: number }` | Yes | Fewer members are required |
Extra properties exist at runtime
Assignability only looks at the declared type. A value typed as Point can carry more properties when the program runs, as p3 did above. Code that enumerates a value's properties therefore cannot assume it sees only the declared ones:
interface Point {
x: number;
y: number;
}
function sum(p: Point): number {
let total = 0;
for (const k of Object.keys(p)) {
// k is string, so p[k] would not compile without a cast
total += p[k as keyof Point];
}
return total;
}
console.log(sum({ x: 1, y: 2 }));Object.keys returns string[], not ("x" | "y")[], because the argument might be the p3 object with a third key. The cast silences the compiler. If someone passes { x: 1, y: 2, z: 3 } through a variable, then Object.keys returns three keys, and p["z" as keyof Point] reads a property that is not in the type. Here it works by luck, since the value is a number. With an extra property of another type, the sum would be wrong, and the compiler would not warn you. When you need exactly the declared properties, name them explicitly (p.x + p.y) instead of iterating.
Common errors
- Expecting a name check. Developers coming from Java or C# expect
Vecto be rejected forPoint. It is not, unless private or protected members are involved. - Reading the error backwards. "Property 'y' is missing in type A but required in type B" means A is the source and B is the target. Fix the source, or make the member optional in the target.
- Assuming a parameter type limits what a caller passes. A parameter of type
Pointaccepts any value that has the shape, including values with many more properties. - Trusting the type for runtime contents. Spreading or serializing a value typed as a small interface can include properties you did not expect, such as extra fields from a database row or an API response.
Exercise
Given interface Named { name: string } and const dog = { name: "Rex", legs: 4 };, is const n: Named = dog; accepted? What about const d: { name: string; legs: number } = n;, and why?
Show answer
The first assignment is accepted. dog has name: string, and the extra legs property is ignored when comparing against Named. The second assignment is an error: n is typed as Named, which lacks the required member legs, so TypeScript reports that property 'legs' is missing. The check depends on the declared type of the variable, not on the object that is actually stored in it.
Exercise
Why does Object.keys(p) have type string[] when p is declared as Point with members x and y?
Show answer
Assignability allows values with extra properties to be used as a Point, so at runtime p may have keys other than x and y. Typing the result as ("x" | "y")[] would be wrong for those values, so TypeScript uses the safe type string[].