【发布时间】:2023-03-24 14:36:02
【问题描述】:
谁能解释它是如何发生的以及为什么? 是错误还是我错过了什么?
function isString<T>(arg:T):boolean {
return (typeof(arg)==='string')?true:false;
}
let myEcho;
myEcho = isString;
let myInt :number = 5;
console.log(myInt + ", Type is "+ typeof(myInt)) // 5, Type is number
myInt = myEcho("hi");
console.log(myInt + ", Type is "+ typeof(myInt)) // true, Type is boolean
我将 myInt 定义为一个数字,但它变成了布尔值!!!
【问题讨论】:
-
您将其 first 定义为一个数字,方法是为其分配 5(一个数字),但随后您将一个布尔值(
myEcho("hi")的结果)重新分配给它变量(myInt),覆盖初始值(5)。 -
@AlexSzabó 在 TypeScript 中,我们无法更改变量的类型,但在这里它会发生变化。问题是它为什么会改变?
-
我的猜测是
myEcho是any类型(因为它声明时没有类型并且它无法推断函数的类型isString- 更具体地说,我认为它无法推断出输入该函数的签名),所以它不会抱怨。
标签: typescript types typescript-generics