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没有抱怨。但是如果我试图在其他地方使用类库,并尝试做同样的事情,它就不会识别它。
当前回答
只需要在你的类中使用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 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!!!");
}
以下是这个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的两个属性都被简单地附加到导出函数(作为其属性);因此,只要正确地访问函数本身,就应该可以访问它们。
谢谢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!)
只需要在你的类中使用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);
你可以使用命名空间,像这样:
export namespace Library {
export const BOOK_SHELF_NONE: string = 'NONE';
}
然后你可以从其他地方导入它:
import {Library} from './Library';
console.log(Library.BOOK_SHELF_NONE);
如果你需要一个类,也可以将它包含在命名空间中: