TypeScript中有公共静态常量吗?我有这样一个类:
export class Library {
public static BOOK_SHELF_NONE: string = "None";
public static BOOK_SHELF_FULL: string = "Full";
}
在那门课上,我可以做图书馆。BOOK_SHELF_NONE和tsc没有抱怨。但是如果我试图在其他地方使用类库,并尝试做同样的事情,它就不会识别它。
TypeScript中有公共静态常量吗?我有这样一个类:
export class Library {
public static BOOK_SHELF_NONE: string = "None";
public static BOOK_SHELF_FULL: string = "Full";
}
在那门课上,我可以做图书馆。BOOK_SHELF_NONE和tsc没有抱怨。但是如果我试图在其他地方使用类库,并尝试做同样的事情,它就不会识别它。
当前回答
下面的解决方案也适用于TS 1.7.5。
// Constancts.ts
export const kNotFoundInArray = -1;
export const AppConnectionError = new Error("The application was unable to connect!");
export const ReallySafeExtensions = ["exe", "virus", "1337h4x"];
使用方法:
// Main.ts
import {ReallySafeExtensions, kNotFoundInArray} from "./Constants";
if (ReallySafeExtensions.indexOf("png") === kNotFoundInArray) {
console.log("PNG's are really unsafe!!!");
}
其他回答
只需要在你的类中使用export变量和import变量
export var GOOGLE_API_URL = 'https://www.googleapis.com/admin/directory/v1';
// default err string message
export var errStringMsg = 'Something went wrong';
现在用它,
import appConstants = require('../core/AppSettings');
console.log(appConstants.errStringMsg);
console.log(appConstants.GOOGLE_API_URL);
以下是这个TS片段编译成(通过TS游乐场):
define(["require", "exports"], function(require, exports) {
var Library = (function () {
function Library() {
}
Library.BOOK_SHELF_NONE = "None";
Library.BOOK_SHELF_FULL = "Full";
return Library;
})();
exports.Library = Library;
});
如您所见,定义为public static的两个属性都被简单地附加到导出函数(作为其属性);因此,只要正确地访问函数本身,就应该可以访问它们。
如果你确实想要在现代浏览器中表现得更像一个静态常量值(因为它不能被其他代码更改),你可以向Library类添加一个get only访问器(这只适用于ES5+浏览器和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);
如果运行它,您将看到试图将BOOK_SHELF_NONE属性设置为新值是如何失败的。
2.0
在TypeScript 2.0中,你可以使用readonly来实现非常相似的结果:
export class Library {
public static readonly BOOK_SHELF_NONE = "None";
public static readonly BOOK_SHELF_FULL = "Full";
}
语法更简单,也更明显。但是,编译器阻止的是更改,而不是运行时(与第一个示例不同,在第一个示例中,根本不允许更改,如所示)。
下面的解决方案也适用于TS 1.7.5。
// Constancts.ts
export const kNotFoundInArray = -1;
export const AppConnectionError = new Error("The application was unable to connect!");
export const ReallySafeExtensions = ["exe", "virus", "1337h4x"];
使用方法:
// Main.ts
import {ReallySafeExtensions, kNotFoundInArray} from "./Constants";
if (ReallySafeExtensions.indexOf("png") === kNotFoundInArray) {
console.log("PNG's are really unsafe!!!");
}
谢谢WiredPrairie!
为了进一步扩展您的答案,这里有一个定义常量类的完整示例。
// CYConstants.ts
class CYConstants {
public static get NOT_FOUND(): number { return -1; }
public static get EMPTY_STRING(): string { return ""; }
}
export = CYConstants;
使用
// main.ts
import CYConstants = require("./CYConstants");
console.log(CYConstants.NOT_FOUND); // Prints -1
console.log(CYConstants.EMPTY_STRING); // Prints "" (Nothing!)