I have a very simple example where TypeScript (3.5.1) is fine with the code, but it immediately throws an error when run.
I believe the issue here is that essentially value
is declared but not initialized prior to getValue
running. This is pretty unintuitive imo but I understand this is how JS works.
However, why can't TS detect this issue in such a simple example? Since value
is a const, it seems to me TS should be able to determine exactly when it's set and predict that this code crashes.
console.log(getValue());
const value = "some string";
function getValue() {
return value;
}
In a second example without a function call, TS does catch that the variable is used before assignment:
console.log(value);
const value = "some string";
TSLint's no-use-before-declare also does not appear applicable.
Assuming TS/linting will not be able to catch this, is there a best practice to apply in the initial example that will avoid this crash? "Always declare module-level consts at top of file" for example.
The error "Variable is used before being assigned" occurs when we declare a variable without assigning a value to it or only assign a value if a condition is met. To solve the error, change the variable's type to be possibly undefined or give it an initial value.
Typescript constants are variables, whose values cannot be modified. We declare them using the keyword const . They are block-scoped just like the let keyword. Their value cannot be changed neither they can be redeclared. Const keyword is part of the es2015 (es6) specification of the javascript.
With TypeScript being an extension of JavaScript, the language naturally supports let and const . Here we'll elaborate more on these new declarations and why they're preferable to var .
The const keyword was introduced in ES6 (2015). Variables defined with const cannot be Redeclared. Variables defined with const cannot be Reassigned.
You could enable tslint's only-arrow-functions
and then replace your function getValue()
with
const getValue = function(): string {
return value;
}
or even
const getValue = (): string => value;
At that point your first line will be a compiler error:
Block-scoped variable 'getValue' used before its declaration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With