我正在尝试通过JSON对象值分配对象并将其返回
interface Input {
vehicles: Vehicle[];
costs: Cost;
}
function readInput(fileName: string): Input{
let input: Input;
readFile(fileName, function (err, data) {
if (err) {
throw err;
}
input = JSON.parse(data.toString("utf8"));
});
return input;
}
输入变量已经“使用”为let input: Input
,这似乎是错误的。这是来自带有tsc -w
命令的终端
src/input.ts(43,12): error TS2454: Variable 'input' is used before being assigned.
19:22:01 - Compilation complete. Watching for file changes.
答案 0 :(得分:2)
对TextBox3.Value = (Val(TextBox1.Value) + Val(TextBox2.Value))
变量的唯一分配是传递给input
的回调函数。
Typescript无法仅从静态类型分析中确定将确实进行赋值(例如readFile
可能就是这种情况),甚至决定是否会调用回调函数(即可以实现if (err)
以这种方式永远不会调用你的函数。
此外,通过函数readFile
的名称判断似乎是异步的,这意味着在 readFile
已经完成其后,很可能会调用的回调执行。
考虑到所有这些因素,打字稿无法保证在readInput()
点之前会对该变量进行分配(并且我相信它确实赢得了#t; t定)。