How to have a property that is read-only

Read-only fields can be initialized once and don't need to be changed during the lifetime of the instance. The readonly keyword can be used in an interface to specify that once the field is set, the value doesn't change:

interface I1 {
readonly id: string;
name: string;
}

let i1: I1 = {
id: "1",
name: "test"
}

i1.id = "123"; // Does not compile

It can be at the class level where the value can be only set directly at the declaration or in the constructor. When a value is initialized next to the field's declaration, this one can still be redefined by the constructor. The following example shows this edge case. However, it is possible to only set it at declaration or just at the constructor level, which is often the case:

class C1 {
public readonly id: string = "C1";

constructor() {
this.id = "Still can change";
}

public f1(): void {
this.id = 1; // Doesn't compile
}
}

Read-only with static can be useful to have constant for a particular class. The use of const is not allowed at a class level. If you want to centralize a value in the context of a particular class, the use of public, static, and readonly is an acceptable pattern:

class C2 {
public static readonly MY_CONST: string = "TEST";
public codeHere(): void {
C2.MY_CONST;
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.102.198