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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…