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

TypeScript two digits addition returns a string concatenation

const x = 1;
const y = ('3' as unknown) as number;

let add = (num1: number, num2: number)=> {
    return num1 + num2;
}

console.log(add(x, y));

// prints 13

Where it is supposed to print 4
as "const y" is converted to "number" type

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 :

const y = ('3' as unknown) as number; is not converting the string to a number. You are only doing a type assertion here.

So, what JS is doing : 1 + '3' = 13.

You would need to do something like Number('3') to fix that issue. But be wary, Number() can return NaN.

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