Property Modifiers in TypeScript
Property Modifiers in TypeScript
Section titled “Property Modifiers in TypeScript”Optional Properties
Section titled “Optional Properties”interface Config { url: string; timeout?: number; retries?: number; headers?: Record<string, string>;}
// Usageconst config: Config = { url: "https://api.example.com" };Readonly Properties
Section titled “Readonly Properties”interface User { readonly id: string; readonly createdAt: Date; name: string;}
const user: User = { id: "1", createdAt: new Date(), name: "Alice" };// user.id = "2"; // ❌ ErrorBranded Types (Nominal Typing)
Section titled “Branded Types (Nominal Typing)”type Brand<T, B> = T & { __brand: B };
type UserId = Brand<string, "UserId">;type OrderId = Brand<string, "OrderId">;
function getUser(id: UserId): User { /* ... */ }function getOrder(id: OrderId): Order { /* ... */ }
const userId = "abc" as UserId;const orderId = "xyz" as OrderId;
getUser(userId); // OKgetUser(orderId); // ❌ Error even though both are strings!Interview Questions
Section titled “Interview Questions”Easy: What does the ? after a property name mean?
Medium: How does readonly differ from const?
Hard: What are branded types and when would you use them?