Skip to content
Back to blog
February 22, 20266 min read

TypeScript Patterns I Use Every Day

TypeScriptBest Practices

Beyond Basic Types


TypeScript's type system is incredibly powerful, but most codebases only scratch the surface. Here are patterns I reach for daily that have saved me from countless bugs.


Discriminated Unions for State Machines


Instead of optional fields and boolean flags, model your state explicitly:


type RequestState<T> =

| { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: T } | { status: 'error'; error: Error };

function handleState(state: RequestState<User>) {

switch (state.status) {

case 'success':

// TypeScript knows state.data exists here return renderUser(state.data);

case 'error':

// TypeScript knows state.error exists here return renderError(state.error);

}

}


Branded Types for Domain Safety


Prevent mixing up primitive types that represent different things:


type UserId = string & { readonly __brand: 'UserId' };

type PostId = string & { readonly __brand: 'PostId' };


function getUser(id: UserId) { /* ... */ }


const userId = "abc" as UserId;

const postId = "xyz" as PostId;


getUser(userId); // ✅

getUser(postId); // ❌ Type error!


The `satisfies` Operator


One of TypeScript's best recent additions. It validates a type without widening it:


const config = {

api: 'https://api.example.com',

timeout: 5000,

retries: 3,

} satisfies Record<string, string | number>;

// config.api is still typed as string, not string | number


Key Takeaways


These patterns aren't clever tricks — they're guardrails that catch bugs at compile time instead of runtime. The best TypeScript code reads like documentation of your domain logic.


T

Tareq Hassan

Full-stack developer building for the web. Open-source contributor and lifelong learner.