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

Is a number of type never?

A small snippet of code is breaking my head:

   var label: number= 12354;
   if(typeof(label) == 'number'){
      label =label.toString();
   }

But it’s giving an error in toString: The property ‘toString’ does not exist in type ‘never’. But it is a number! Why does inside if say it is of type never? If you change label to type any, the errors will be eliminated. I want to know why typescript ignored validation and stated something impossible in the presented context?

    //Expectation
    label = '12345';
    //Reality:
     Property 'toString' does not exist in type 'never'.ts(2339)

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

>Solution :

Try this way

var label: number | string = 12354;

if (typeof label === 'number') {
  label = label.toString();
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