TSC之后静态成员失踪

问题描述 投票:0回答:1

我有一个包含在打字稿中声明为静态的全局值的类。

看起来像这样:

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;

我的问题是,我的会员怎么了!?

欢迎任何想法:)

typescript tsc
1个回答
0
投票

您实际上并不是在分配成员,而是将它们定义为具有类型的未定义变量。使用=代替:

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允许字符串和整数常量作为类型使用,这样,如果您传入的字符串和整数常量不是其中之一,则接受leftright的参数将引发编译时错误两个值。与对象定义(例如{foo: "bar"})不同,您定义了class,并且TypeScript中的类字段使用:定义类型,并使用=定义值。

[我认为TypeScript不会抱怨据说不接受undefined很有趣,但这是一个单独的问题。


0
投票

在我看来,您是在这里将静态变量的类型声明为静态变量的预期值。例如:

public static APP_ID: "appidstringhere"

当您应该说:APP_ID的类型为"appidstringhere"时:

public static APP_ID: string = "appidstringhere"

表示APP_ID的类型为string,并且值为"appidstringhere"

© www.soinside.com 2019 - 2024. All rights reserved.