Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why function expression and function declaration have different inference results for a variable?

I have a variable and three function:

const a: string | number = 3

function b(){
  console.log(a)               // string | number 
}
const c = function (){
  console.log(a)               // number
}
const d = () => {
  console.log(a)               // number
}

When I hovered the word a in function b, what I got is string | number;

When I hovered the word a in function c, what I got is number;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I hovered the word a in function d, what I got is number

But isn’t a a constant? After the first time it was assigned the value 3, a have been infered to become a number type. Why in function b it still have a chance to become a string type?

>Solution :

I believe it’s because of function hoisting. In theory, b could be called before a has its value definitely assigned:

b(); // <=====
const a: string | number = 3

function b(){
  console.log(a)               // string | number 
}
const c = function (){
  console.log(a)               // number
}
const d = () => {
  console.log(a)               // number
}

Neither c nor d can be called from there, they aren’t assigned until after a is definitely assigned.

From a runtime perspective, the call to b would throw when trying to access a because a would be in the temporal dead zone, but from a type perspective, it would be before TypeScript knew it was a number.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading