Workarounds: Type Assertions
What you'll learn: How to use type assertions to explicitly bypass excess property checks when you're certain an object is correct.
The Core Idea
Sometimes you know an object is valid, but TypeScript's excess property checks won't let you pass it directly to a function or assign it to a typed variable. Type assertions let you tell the compiler "trust me, I know what I'm doing" — essentially overriding the freshness check.
Think of it like showing a security guard your VIP badge to skip the line. The normal rules still exist, but you're using your authority to bypass them.
Using Type Assertions
You've already learned that assigning to a variable avoids excess properties checks. Type assertions are another escape hatch — you explicitly cast the object to the target type:
type Person = {
name: string;
age: number;
};
function greet(person: Person) {
console.log(`Hello, ${person.name}`);
}
// This triggers excess property check - ERROR!
// greet({ name: "Alice", age: 30, hobby: "reading" });
// Workaround: Type assertion
greet({ name: "Alice", age: 30, hobby: "reading" } as Person);
// ✓ Works — assertion bypasses the check
The as Person tells TypeScript to treat the object literal as a Person type, making it "non-fresh" and skipping the excess property validation.
When to Use This
This workaround is useful when you're receiving data from an external source or legacy code that includes extra properties you can't control. However, use it sparingly — you're turning off a safety feature that helps catch typos and misunderstandings.
Key Takeaway: Type assertions with as Type let you explicitly opt out of excess property checking, but they bypass TypeScript's safety nets and should be used only when you're confident the object is correct.