Typescript – public static const in TypeScript

typescript

Is there such a thing as public static constants in TypeScript? I have a class that looks like:

export class Library {
  public static BOOK_SHELF_NONE: string = "None";
  public static BOOK_SHELF_FULL: string = "Full";
}

In that class, I can do Library.BOOK_SHELF_NONE and the tsc doesn't complain. But if I try to use the class Library elsewhere, and try to do the same thing, it doesn't recognize it.

Best Answer

If you did want something that behaved more like a static constant value in modern browsers (in that it can't be changed by other code), you could add a get only accessor to the Library class (this will only work for ES5+ browsers and NodeJS):

export class Library {
    public static get BOOK_SHELF_NONE():string { return "None"; }
    public static get BOOK_SHELF_FULL():string { return "Full"; }   
}

var x = Library.BOOK_SHELF_NONE;
console.log(x);
Library.BOOK_SHELF_NONE = "Not Full";
x = Library.BOOK_SHELF_NONE;
console.log(x);

If you run it, you'll see how the attempt to set the BOOK_SHELF_NONE property to a new value doesn't work.

2.0

In TypeScript 2.0, you can use readonly to achieve very similar results:

export class Library {
    public static readonly BOOK_SHELF_NONE = "None";
    public static readonly BOOK_SHELF_FULL = "Full";
}

The syntax is a bit simpler and more obvious. However, the compiler prevents changes rather than the run time (unlike in the first example, where the change would not be allowed at all as demonstrated).