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 theLibrary
class (this will only work for ES5+ browsers and NodeJS):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: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).