Reputation: 2773
I would like to understand the following TypeScript behavior:
The following code
let a: number
if (a === undefined) {
console.log("how?")
}
throws an error: "Variable 'a' is used before being assigned.".
But the following code
let a: number
const f = (): void => {
if (a === undefined) {
console.log("how?")
}
}
f()
works just fine and logs "how?".
Why is that? And also, how come a === undefined
if its type is number
?
Upvotes: 5
Views: 1714
Reputation: 360
To deal with the error Variable 'a' is used before being assigned.
the simple solution I think is to declare the variable as either number
or undefined
, instead of just number
.
let a: number | undefined
One other pattern is just to initialize a variable with a value:
let a: number = 0
I used that pattern a lot in C# years ago, but I don't personally care for that pattern in JavaScript and prefer what you have of leaving a variable un-set if the conditions to assign it a value are conditional.
Upvotes: 4
Reputation: 111
For the second question: in TS, variables not initialized are always undefined
, despite of their type. This is different, for example, from C# where a variable typed bool
is always true or false and initialized as false. In TS that variable could be also undefined and, if I remember well, also null. So sometimes is good to write
if( testVariable === false)
instead of simply
if( !testVariable )
Upvotes: 1
Reputation: 3711
There's an open issue about this in the Typescript GitHub project. It's a limitation of typescript's technical design.
From Ryan Cavanaugh, it's
because we don't inline the flow-control effects of functions
Upvotes: 3