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
CodePudding user response:
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
.