Explain the concept and benefits of using the 'readonly' modifier in TypeScript classes or interfaces.

Instruction: Provide a detailed explanation and example code to illustrate your answer.

Context: This question assesses the candidate's understanding of restricted assignment through readonly properties, including the limits of shallow compile-time enforcement and mutable aliases.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

readonly prevents assignment through that property in checked TypeScript code. For a class property, initialization can occur in its declaration or constructor. It documents a restricted write contract; it does not freeze the object at runtime or recursively make referenced values immutable.

```typescript class User { constructor( readonly id: number, readonly createdAt: Date ) {} } interface Named { readonly name: string...

Related Questions