为什么TypeScript在分配之前没有捕获到正在使用const?

Luk*_*ams 9 typescript

我有一个非常简单的示例,其中TypeScript(3.5.1)可以很好地使用代码,但运行时会立即引发错误。

我相信这里的问题是本质上value是在运行之前声明但未初始化的getValue。这是非常不直观的imo,但我知道这是JS的工作方式。

但是,为什么在这样一个简单的示例中TS无法检测到此问题?由于value是const,在我看来TS应该能够准确确定设置的时间并预测此代码将崩溃。

console.log(getValue());

const value = "some string";

function getValue() {
  return value;
}
Run Code Online (Sandbox Code Playgroud)

在没有函数调用的第二个示例中,TS确实发现在赋值之前使用了变量:

console.log(value);
const value = "some string";
Run Code Online (Sandbox Code Playgroud)

TSLint的声明前无用似乎也不适用。

假设TS /棉绒将无法捕捉到这一点,那么在初始示例中是否有最佳实践来避免这种崩溃?例如,“始终在文件顶部声明模块级const”。

dan*_*xon 3

您可以启用 tslint only-arrow-functions,然后将其替换function getValue()

const getValue = function(): string {
  return value;
}
Run Code Online (Sandbox Code Playgroud)

甚至

const getValue = (): string => value;
Run Code Online (Sandbox Code Playgroud)

那时你的第一行将是一个编译器错误:

Block-scoped variable 'getValue' used before its declaration
Run Code Online (Sandbox Code Playgroud)