We want to make sure objects have the right properties without mistakes. Excess property checks help catch extra wrong properties, while structural compatibility lets objects work if they have the needed parts.
Excess property checks vs structural compatibility in Typescript
interface Person {
name: string;
age: number;
}
const p: Person = { name: "Alice", age: 30, location: "NY" };Excess property checks happen when you assign an object literal directly to a variable or parameter expecting a specific type.
Structural compatibility means TypeScript checks if an object has at least the required properties, ignoring extra ones when not assigned directly.
location is not in Person.interface Person {
name: string;
age: number;
}
// Excess property check error
const p1: Person = { name: "Bob", age: 25, location: "LA" };Person works because of structural compatibility.interface Person {
name: string;
age: number;
}
const extra = { name: "Bob", age: 25, location: "LA" };
const p2: Person = extra; // No error herehobby causes an error.function greet(person: Person) { console.log(`Hello, ${person.name}`); } greet({ name: "Eve", age: 28, hobby: "reading" }); // Error: excess property 'hobby'
const obj = { name: "Eve", age: 28, hobby: "reading" }; greet(obj); // No error because obj is a variable
This program shows how excess property checks cause an error when assigning an object literal with extra properties directly. But assigning a variable with extra properties to the expected type works fine.
interface Car {
make: string;
year: number;
}
// Direct object literal with extra property - error
// const car1: Car = { make: "Toyota", year: 2020, color: "red" };
// Using a variable with extra property - no error
const carDetails = { make: "Toyota", year: 2020, color: "red" };
const car2: Car = carDetails;
console.log(car2.make);
console.log(car2.year);Excess property checks only happen on fresh object literals assigned directly.
Structural compatibility allows objects with extra properties to be assigned if they come from variables.
You can use type assertions or index signatures to bypass excess property checks if needed.
Excess property checks catch extra properties in direct object literals to prevent mistakes.
Structural compatibility allows objects with extra properties to be used if assigned from variables.
This helps balance safety and flexibility in TypeScript object typing.