0

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.

Example stackblitz

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?

0

2 Answers 2

2

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 }[]>;

Full example

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for explaining in detail, that makes a lot sense. Anyway, fyi, your stackblitz doesn't work though. Not that it matters cause your answer does explain everything but do remember to press the fork button next time =P
Thanks for letting me know about link.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.