Menu

1 / 2

The Art of the Side Project: How to Ship Fast and Validate Early

DEV Community·Alex Chen·5 months ago
#cs37rFgb
Reading 0:00
15s threshold

7 TypeScript Patterns I Use in Every Project

These aren't groundbreaking. They're the boring patterns that prevent bugs and save hours of debugging.

1. The Result Type (No More try/catch Hell)

// Instead of throwing exceptions everywhere: function divide ( a : number , b : number ): number { if ( b === 0 ) throw new Error ( " Division by zero " ); return a / b ; }

// Use a Result type: type Result < T , E = Error > = | { ok : true ; value : T } | { ok : false ; error : E };

function divide ( a : number , b : number ): Result < number , string > { if ( b === 0 ) return { ok : false , error : " Division by zero " }; return { ok : true , value : a / b }; }

// Usage — the compiler FORCES you to handle errors: const result = divide ( 10 , 0 ); if ( result . ok ) { console . log ( result . value ); // TypeScript knows this is number } else { console . error ( result .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.