
TypeScript Tips That Changed How I Write Code
TypeScript is more than adding : string to your variables. Here are the patterns that level up your TypeScript code. 1. Discriminated Unions The most powerful pattern in TypeScript for handling different shapes of data: type ApiResponse = | { status : ' success ' ; data : User [] } | { status : ' error ' ; message : string } | { status : ' loading ' }; function handleResponse ( response : ApiResponse ) { switch ( response . status ) { case ' success ' : // TypeScript knows response.data exists here return response . data . map ( u => u . name ); case ' error ' : // TypeScript knows response.message exists here console . error ( response . message ); return []; case ' loading ' : return null ; } } 2. Type Guards That Actually Work // Simple type guard function isString ( value : unknown ): value is string { return typeof value === ' string ' ; } // Object type guard function isUser ( obj : unknown ): obj is User { return ( typeof obj === ' object ' && obj !== null && ' id ' in obj && '
Continue reading on Dev.to Tutorial
Opens in a new tab



