readonly
A modifier, in languages such as C# and TypeScript, that lets a field or property be assigned only when it is initialised, never afterwards.
In more detail
It protects values that should not change after construction, such as injected dependencies. It restricts reassignment only; an object held in a readonly field can still change its own contents.
Examples
private readonly IProductRepository _repository;readonly id: string;type Point = readonly [number, number];Related terms
- field — A variable declared inside a class that stores part of an object's state.
- primary constructor — Constructor parameters written straight after a class name, as in class ProductService(IProductRepository repository), which stay in scope for the whole class body.
- immutable — Something that cannot be changed after it is created; to change it you make a new one.
- Readonly<T> — The utility type that marks every top-level property of T as readonly.
- as const — The TypeScript suffix as const, which tells the compiler to treat an object's values as fixed literal values rather than general types.
- mapping modifier — A plus or minus sign before readonly or the optional question mark in a mapped type, which adds or removes that modifier from every property.
Taught in
- Classes, Interfaces, and Object-Oriented C# — Modern .NET Core, C# & Enterprise Microservices
- Records, Pattern Matching, and Modern C# — Modern .NET Core, C# & Enterprise Microservices
- Literal Types: String, Number, Boolean Literals And const — Production TypeScript
- Type Aliases Versus Interfaces: Declaration Merging — Production TypeScript
- Optional Properties, Readonly And Index Signatures — Production TypeScript
- Union Types, Intersections And Property Conflicts — Production TypeScript
- Tuples: Fixed Length, Labeled Elements And Variadic Tuples — Production TypeScript
- Const Type Parameters: Retaining Literal Types In Functions — Production TypeScript
- Core Utilities: Partial, Required, Readonly, Pick And Omit — Production TypeScript
- Mapped Types, Key Remapping With as And Template Literals — Production TypeScript