Excess Property Checks in TypeScript
Excess Property Checks in TypeScript
Section titled “Excess Property Checks in TypeScript”When Excess Checking Applies
Section titled “When Excess Checking Applies”interface User { name: string; age: number;}
// Direct object literal — checked strictlyconst user: User = { name: "Alice", age: 30, email: "alice@test.com" };// ❌ Error: 'email' does not exist in type 'User'
// Variable assignment — structural checks onlyconst userData = { name: "Alice", age: 30, email: "alice@test.com" };const user2: User = userData; // OK — structural compatibilityCommon Workarounds
Section titled “Common Workarounds”// 1. Intermediate variableconst data = { name: "Alice", age: 30, extra: true };const user: User = data;
// 2. Spread operatorconst user: User = { name: "Alice", age: 30, ...{ extra: true } };
// 3. Type assertion (careful!)const user = { name: "Alice", age: 30, extra: true } as User;
// 4. Index signature for flexibilityinterface FlexibleUser { name: string; age: number; [key: string]: unknown;}Interview Questions
Section titled “Interview Questions”Easy: What is excess property checking?
Medium: When does TypeScript perform excess property checking?
Hard: How can you allow extra properties on an object type?