#Why does TS Narrow variables with a type annotation?

8 messages · Page 1 of 1 (latest)

pallid path
#

Can someone explain this behavior? I explicitly annotated a variable to boolean and it's not a constant. But TS typeof operator narrows the type and uses the current value.

let a: boolean = true;
//  ^? let a: boolean 
type A = typeof a;
//   ^? type A = true
whole warren
#

It knows at this point of execution a must be true.

#

If you add a line of a = false then it changes to a different type.

pallid path
#

It's annotated with boolean.

#

What you said make sense for this scenario

let a = true;
type A = typeof a
subtle idol
#

TS ignores the annotation because it can

#

You can use let a = true as boolean if it's a problem

#

Or just write write the A type first and use that to type a rather than the opposite flow