Reputation: 37
I'm having a compilation error with the code provided in the playground link and I don't understand why.
I'm creating a variable with a value of an enum:
intellisense tell me that the type of my variable is inferred as I expected: ValidatorMessageState. Like when assigning true/false to a variable, typescript infers a boolean and not true or false as type.
then I switch over it:
Now intellisense tells me the type of my variable has changed even if I've done nothing between creating it and switching on it.
Variable have now the type of the value of the enum and not the enum.
Another thing I've found strange: if I introduce some closure, typescript does not give me errors (I've commented this part in the playground)
I suppose I'm doing something wrong here, but I don't see what. Can someone could explain it to me?
Updated playground: Playground Link
Upvotes: 0
Views: 107
Reputation: 1717
It's a feature, not a bug :)
This is Typescript doing control flow analysis. The control flow analysis only start kicking in in certain code structures, like a switch statement.
Once you reach the switch statement, typescript compiler tries to narrow down the type of maxStateEncoutered
. And in your case it can only be ValidatorMessageState.Error
as that was the only assignement. And typescript isn't wrong about this... If you assigned your variable in some dynamic way (as in: a function that returns ValidatorMessageState
) the error would go away.
As for the code inside the forEach
, typescript can't reason about code inside closures/callbacks. The gist of the reason being it doesn't know when this code will run. Sure, in forEach
it will run immediately, but typescript doesn't know that about the function. In a function like addEventListener
the function you pass can run at any time, and maxStateEncoutered
might change until then, so it can no longer deduce that maxStateEncoutered
is of specific type ValidatorMessageState.Error
. If you change maxStateEncoutered
from let
to const
, you will see this error inside the forEach
as well.
Upvotes: 1