首页 > 解决方案 > 静态变量在打字稿中被初始化为未定义

问题描述

我对 Typescript 和 node.js 有点陌生。我在一个类中声明为静态的变量很少,它们将在调用函数时初始化。我正在尝试在另一个班级中访问它们。有时在尝试访问这些静态变量时会返回 undefined,即使它们已初始化。请在下面找到我的代码:

测试.ts

describe('Test', function () {

let testUtil: TestUtil,

before(async function () {
        await Constants.init_TestConfig();
        testUtil = new TestUtil();
    });

it('Step 1', async function () {
        //Constants.sURL returning the initialized variable
        let url = await Constants.sURL;
        console.log(url);
        await testUtil.loadURL();
    });

});

测试工具.ts

export class TestUtil{

public async loadURL(){
        //Constants.sURL returing undefined here
        let url = await Constants.sURL;
        console.log(url);
    }
}

常量.ts

export class Constants{

public static sURL:string;

public static async init_TestConfig(){
    //initialize URL
    this.sURL = "some URL";
    }
}

Constants.sURL当尝试访问时Test.ts工作正常,但是当我尝试从任何其他类访问相同时,它返回未定义。文件中声明的任何其他变量也是如此Constants.ts

标签: javascriptnode.jstypescript

解决方案


推荐阅读