How to Create a Class Constant Using TypeScript?

Declare a class const in TypeScript

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 the this 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;
    }
}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.