Back to articles
10 TypeScript Tricks That Made Me Mass-Delete Type Assertions From Our Codebase

10 TypeScript Tricks That Made Me Mass-Delete Type Assertions From Our Codebase

via Dev.to WebdevMatthew Hou

Our codebase had 247 instances of as any . After learning these TypeScript patterns, I replaced all but 3 of them with proper type safety. The remaining 3 are interfacing with a genuinely untyped third-party library. Here are the 10 patterns that made as any almost unnecessary. 1. Discriminated Unions (Eliminate Type Guards) // ❌ Before: checking type at runtime type Shape = { kind : string ; radius ?: number ; width ?: number ; height ?: number }; function area ( shape : Shape ): number { if ( shape . kind === ' circle ' ) return Math . PI * shape . radius ! * shape . radius ! ; if ( shape . kind === ' rect ' ) return shape . width ! * shape . height ! ; throw new Error ( ' Unknown shape ' ); } // ✅ After: TypeScript knows the type from the discriminant type Circle = { kind : ' circle ' ; radius : number }; type Rectangle = { kind : ' rectangle ' ; width : number ; height : number }; type Shape = Circle | Rectangle ; function area ( shape : Shape ): number { switch ( shape . kind ) {

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
20 views

Related Articles