Skip to content

Property Modifiers in TypeScript

interface Config {
url: string;
timeout?: number;
retries?: number;
headers?: Record<string, string>;
}
// Usage
const config: Config = { url: "https://api.example.com" };
interface User {
readonly id: string;
readonly createdAt: Date;
name: string;
}
const user: User = { id: "1", createdAt: new Date(), name: "Alice" };
// user.id = "2"; // ❌ Error
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); // OK
getUser(orderId); // ❌ Error even though both are strings!

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?