打字稿泛型:字符串转换为数字并给出正确的输出

function multi <T> (num: T): T {

    let total = num * 3; 
    return total; 
}

let amazing = multi<string>("3");
// or let amazing = multi("3");
// in both cases, I get output number 9.. why?

问题:

  1. 为什么Typescript将显式类型转换为数字并
  2. 给输出数字9?
  3. 为什么当我使用字符串“ 3”并给我输出数字9(在第二种情况下,在注释中)时,Typescript不会抛出任何错误?
评论
女汉子
女汉子

It would not compile in typescript, but would work perfectly fine in compiled javascript ignoring typescript compiling error: javascript converts num to number before * operator.

点赞
评论