就像 Edwin Dalorzo 提到的那样,为所有变量创建一个单独的文件似乎是最好的。
我已经有几个小时遇到了类似的问题,因为我不知道变量是持久的。我的场景是:
我有两个文件 cli.ts 和 main-lib.ts。 cli.ts 读取用户输入,并根据输入运行main-lib.ts 中的函数。当main-lib.ts 忙于验证输入时,cli.ts 使用了main-lib.ts 在测试通过时生成的一些全局变量。唯一的限制是我不能把main-lib.ts代码和cli.ts混在一起,我只能共享函数callValidateFunction。
我最初想到的问题是:如果我要创建一个global-vars.ts 文件,每次调用require 的变量数据仍然会有所不同(即调用setVar(...) 只会改变导入的变量值。
但是,感谢 Edwin 的回答,我设法实现了一座桥梁:
// cli.ts
import { setVar, getVar } from "./var-bridge";
import { callValidateFunction } from "./main-lib";
function run(args: string[]): void {
// ...
if (arg == "--email") {
// Set the test status.
setVar("testStatus", "pending");
// Validate the input email address.
callValidateFunction("validateEmail", nextArg());
// Get the testStatus.
const testStatus: string = getVar("testStatus");
}
// ...
}
// main-lib.ts
import { setVar, getVar } from "./var-bridge";
const funcs: {name: string, func: (arg: string) => boolean} = {};
funcs.validateEmail = function(arg: string): boolean {
let passed: boolean = false;
// ...
return passed;
};
function callValidateFunction(functionName: string, arg: string): void {
// ...
const passed = funcs[functionName](arg);
if (passed) setVar("testStatus", "passed");
}
// ...
// var-bridge.ts
const variables: {name: string, value: any} = {
"testStatus": "",
// ...
};
function setVar(varName: string, varValue: any): void {
variables[varName] = varValue;
}
function getVar(varName: string): any {
return variables[varName];
}
export { setVar, getVar };