~/swaraj.dev
Back to all posts
May 6, 20261 min read

Branded Types in TypeScript: Safeguarding IDs in React Native

Learn how TypeScript branded types prevent accidental ID mix‑ups, making your React Native code safer and more self‑documenting.

typescriptreact nativetype safety

Insight

In mobile apps, string IDs for users, posts, or products are everywhere. A simple typo or copy‑paste error can cause a function expecting a userId to receive a postId, leading to runtime bugs that are hard to trace. TypeScript's branded types let you create distinct compile‑time types from the same primitive, giving the compiler a chance to catch those mix‑ups before they ship.

Example

// Define unique brands for each ID type
type UserId = string & { readonly __brand: unique symbol };
type PostId = string & { readonly __brand: unique symbol };

// Helper factories (runtime‑no‑op) for clarity
const asUserId = (id: string): UserId => id as UserId;
const asPostId = (id: string): PostId => id as PostId;

function fetchUserPosts(userId: UserId) {
  // fetch logic …
}

// Correct usage
fetchUserPosts(asUserId('u-42'));

// Uncommenting the line below triggers a TypeScript error
// fetchUserPosts(asPostId('p-99')); // ❌

Takeaway

Adopt branded types for any identifier that crosses module boundaries. A single extra line of type definition gives you compile‑time safety without runtime overhead, keeping your React Native codebase robust as it scales.