capypad
0 day streak
typescript / beginner
Snippet

Readonly Properties in Interfaces

The 'readonly' modifier ensures that a property can only be assigned a value when the object is first created, preventing later modifications.

snippet.ts
typescript
1
2
3
4
5
6
7
interface UserProfile {
readonly id: number;
username: string;
}
 
const user: UserProfile = { id: 99, username: "coder123" };
// user.id = 100; // This would cause a compile error
Breakdown
1
readonly id: number;
Marks the 'id' property as read-only, preventing reassignment after initialization.
2
user.id = 100;
Demonstrates that trying to change a readonly property results in a TypeScript error.