Tarek.
← All posts

TypeScript Advanced Patterns: Branded Types, Template Literals, and More

· 1 min read · Admin

Branded Types

typescript
type UserId = string & { readonly __brand: "UserId" };type PostId = string & { readonly __brand: "PostId" };​function createUserId(id: string): UserId { return id as UserId; }function getUser(id: UserId) { /* ... */ }​const userId = createUserId("abc-123");getUser(userId);  // WorksgetUser("xyz" as PostId);  // Compile error!

Template Literal Types

typescript
type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE";type Endpoint = "/users" | "/posts";type Route = `${HTTPMethod} ${Endpoint}`;// "GET /users" | "GET /posts" | ... (8 combinations)

Conditional Types

typescript
type Unwrap<T> = T extends Promise<infer U> ? U : T;type Result = Unwrap<Promise<string>>;  // string

Utility Types You Should Know

  • Partial<T> — all properties optional

  • Required<T> — all properties required

  • Pick<T, K> — extract subset

  • Omit<T, K> — remove properties

  • Record<K, V> — key-value types

  • ReturnType<F> — extract return type