There's an interesting scenario I came across where TypeScript (3.5.1) seems to approve of the code, but it throws an error as soon as it is executed.
It appears that the root cause lies in the fact that value
is being declared without being initialized before the function getValue
is called. This behavior may seem counterintuitive, but I recognize that this is how JavaScript operates.
One might wonder why TypeScript doesn't detect such a simple issue. Given that value
is declared as a const, one would expect TS to trace when it gets assigned and anticipate the crash in this situation.
console.log(getValue());
const value = "some string";
function getValue() {
return value;
}
In another example without a function call, TypeScript correctly identifies that the variable is being used before assignment:
console.log(value);
const value = "some string";
Furthermore, TSLint's no-use-before-declare rule does not seem to be relevant here.
If we assume that TypeScript and linting won't catch this issue, is there a best practice to prevent this crash in the initial example? Perhaps something like "Always declare module-level consts at the top of the file"?