You can prefix class fields with the readonly
modifier (introduced in TypeScript 2) to prevent assignment of values to the field outside the class constructor. However, you can still reassign a readonly
class field in the constructor:
// TS2+ class Foo { public readonly BAR: number = 123; constructor() { this.BAR = 321; } }
For this reason, you need to define the class field as static readonly
:
// TS2+ class Foo { public static readonly BAR = 123; // ... }
This works because static
fields are only accessible on:
- The class itself (e.g.
MyClass.staticField
), and; - The
this
context of static methods (but not on thethis
context of instance methods).
Therefore, trying to assign a value to a static readonly
field in the class constructor would throw an error:
// TS2+
class Foo {
public static readonly BAR: number = 123;
constructor() {
// Error: Property 'BAR' does not exist on type 'Foo'. Did you mean to access the static member 'Foo.BAR' instead?
this.BAR = 321;
}
}
// TS2+
class Foo {
public static readonly BAR: number = 123;
constructor() {
// Error: Cannot assign to 'BAR' because it is a read-only property.
Foo.BAR = 321;
}
}
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.