Sub topic 5
Excess Property Checks on Object Literals
Assume you know basic TypeScript syntax, interfaces, object types, and compiler error messages. This chapter focuses on one special rule in structural typing: excess property checks.
The basic rule
TypeScript usually checks whether a source value has all properties required by the target type. A source may contain additional properties.
An object literal is treated more strictly when it is assigned directly to a target type. TypeScript checks for properties that the target type does not declare. These are called excess property checks.
interface Point {
x: number;
y: number;
}
const point3d = { x: 1, y: 2, z: 3 };
const first: Point = point3d; // OK
// point3d contains x and y, so it can be used as a Point.
const second: Point = { x: 1, y: 2, z: 3 };
// Error: 'z' does not exist in type 'Point'.The two assignments have the same apparent shape, but the first source is a variable and the second source is a fresh object literal.
Why the rule exists
Excess property checks catch spelling mistakes and configuration errors:
interface RequestOptions {
timeout: number;
retries: number;
}
const options: RequestOptions = {
timeout: 5000,
retrise: 2
};
// Error: 'retrise' is not a declared property.
// The intended property was probably 'retries'.The check does not mean that Point rejects every object containing z. It means that TypeScript treats a newly written object literal as a value whose properties you probably intended to describe completely.
Common ways to control the check
Give a variable an explicit type when you want the compiler to validate the complete object:
interface Point {
x: number;
y: number;
}
const point: Point = { x: 1, y: 2 };If extra keys are intentional, declare them with an index signature:
interface Metadata {
name: string;
[key: string]: string;
}
const data: Metadata = {
name: "report",
owner: "Ada"
};Avoid using type assertions merely to silence an error. An assertion can hide a misspelled property rather than fix the object’s design.
Exercise
Why does const p: Point = { x: 1, y: 2, z: 3 } fail when assigning { x: 1, y: 2, z: 3 } to an intermediate variable first succeeds?
Show answer
A fresh object literal receives an excess property check. The intermediate variable is checked structurally, so its extra z property is allowed.