Reputation: 3491
I am trying to make a property in a component read-only. However, it seems like the readonly modifier doesn't do anything at all.
Based on the documentation, I shouldn't be able to modify the cars
property declared in AppComponent once I have initialized in the constructor()
.
What I've tried:
At first I was able to modify cars
in AppComponent's ngOnInit()
and I thought that this is probably an allowed behaviour because the component is still being "constructed". So I created a button that calls a function and tries to modify the property, yet, again I could do so. So I thought maybe the readonly modifier only applies to outside classes accessing the property. But yet, again I am able to modify cars
in HelloComponent
.
Am I using readonly wrongly? How do I use it correctly or make a property accessible in public but not "modified-able" (readonly) by outside?
Upvotes: 0
Views: 1335
Reputation: 3566
readonly This keyword is used in interface or class to mark a property as ready only
class Employee {
readonly empCode: number;
empName: string;
constructor(code: number, name: string) {
this.empCode = code;
this.empName = name;
}
}
let emp = new Employee(10, "John");
emp.empCode = 20; //Compiler Error
emp.empName = 'Bill'; //Compiler Error
Note that property marked readonly can be only assigned value in constructor or when declaring the property.
A property marked readyonly can not be reassigned.
In your code example:
modifyCars() {
this.cars[0] = { id: -1, name: 'MODIFIED BY BUTTON' };
}
You are not reassigning, instead you are mutating array. To prevent array mutation you can use ReadOnly mapped type.
replace
readonly cars;
with
readonly cars: Readonly<{ id: number, name: string }[]>;
Upvotes: 2
Reputation: 27363
TypeScript comes with a ReadonlyArray type that is the same as Array with all mutating methods removed, so you can make sure you don’t change your arrays after creation
cars :ReadonlyArray<any>;
Forked Example: https://stackblitz.com/edit/angular-g8pmdr
Ref:https://www.typescriptlang.org/docs/handbook/interfaces.html#readonly-properties
Upvotes: 0