Type Assertions and Narrowing
The Production Bug That Type Assertion Couldn't Save
TypeError: Cannot read property 'preferences' of undefined
at renderDashboard (dashboard.ts:47)function renderDashboard(userId: string) {
const data = fetchDashboardData(userId);
// I "knew" this would always be DashboardData
const dashboard = data as DashboardData;
return {
theme: dashboard.user.preferences.theme, // Crashed here!
widgets: dashboard.widgets
};
}Type Assertions
as Syntax (Preferred)
Angle Bracket Syntax (Avoid in TSX)
When Type Assertions Are Safe
After Type Guard
With DOM Elements
With JSON Parsing
When Type Assertions Are Dangerous
Overriding Compiler Without Checking
Assuming API Response Shape
Non-Null Assertion Operator (!)
Basic Non-Null Assertion
Safe Uses
Dangerous Uses
as const Assertions
Basic as const
Object as const
Enum Alternative
satisfies Operator
Without satisfies
With satisfies
Catch Errors Early
Type Predicates
Basic Type Predicate
Object Type Predicates
Discriminated Union Type Guard
Advanced Narrowing Techniques
Truthiness Narrowing
Equality Narrowing
instanceof Narrowing
in Operator Narrowing
Discriminated Union Narrowing
Control Flow Analysis
Basic Flow
Complex Flow
Common Mistakes I Made
1. Assertion Without Validation
2. Double Assertion
3. Asserting Constants
Your Challenge
Key Takeaways
What I Learned
Last updated