Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't TypeScript catch that a const is being used before assignment?

Tags:

typescript

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.

like image 634
Freewalker Avatar asked May 29 '19 21:05

Freewalker


People also ask

Is used before being assigned TypeScript?

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.

What does const {} mean in TypeScript?

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.

Can you use const in TypeScript?

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 .

Can you Redeclare a const?

The const keyword was introduced in ES6 (2015). Variables defined with const cannot be Redeclared. Variables defined with const cannot be Reassigned.


1 Answers

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
like image 184
danielnixon Avatar answered Oct 06 '22 03:10

danielnixon