我有一个包含全局值的类,我在typescript中声明它是静态的。
它看起来是这样的:
export default class Globals {
// All members should be public static - no instantiation required
public static GraphAPIToken: null
public static APP_ID: "appidstringhere"
public static APP_SECRET: "thisisasecret"
public static TOKEN_ENDPOINT: "https://login.microsoftonline.com/aaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeeeeeee/oauth2/v2.0/token"
public static MS_GRAPH_SCOPE: "https://graph.microsoft.com/.default"
}使用TSC (Typescript 3.7.3)编译到js后,结果如下:
"use strict";
exports.__esModule = true;
var Globals = /** @class */ (function () {
function Globals() {
}
return Globals;
}());
exports["default"] = Globals;我的问题是,我的成员发生了什么?
欢迎任何想法:)
发布于 2020-02-07 09:25:14
在我看来,您在这里将静态变量的类型声明为静态变量的目标值。例如:
public static APP_ID: "appidstringhere"
这说明APP_ID的类型是"appidstringhere",而您应该这样说:
public static APP_ID: string = "appidstringhere"
这说明APP_ID的类型为string,值为"appidstringhere"。
发布于 2020-02-07 09:24:21
你实际上并没有给你的成员赋值,你只是将它们定义为带有类型的未定义变量。使用=而不是:。
export default class Globals {
// All members should be public static - no instantiation required
public static GraphAPIToken = null;
public static APP_ID = "appidstringhere";
public static APP_SECRET = "thisisasecret";
public static TOKEN_ENDPOINT = "https://login.microsoftonline.com/aaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeeeeeee/oauth2/v2.0/token";
public static MS_GRAPH_SCOPE = "https://graph.microsoft.com/.default";
}附加上下文: TypeScript允许字符串和整数常量作为类型使用,这样,如果传入的字符串不是这两个值之一,接受left和right的参数将抛出编译时错误。与对象定义(如{foo: "bar"} )不同,您定义了一个class,TypeScript中的类字段使用:定义类型,使用=定义值。
我认为有趣的是,TypeScript没有抱怨不应该接受undefined,但这是另一个问题。
https://stackoverflow.com/questions/60105821
复制相似问题