![](/img/trans.png)
[英]What is the difference between using : and => for the return type with a TypeScript function?
[英]What is the difference between typescript function default parameter assignment and type checking?
考虑以下功能
我在以下收获或遗忘了什么
getFruits(checkInventory = true){
if (checkInventory) {}
....
}
getFruits(checkInventory: boolean){
if (checkInventory) {}
....
}
getFruits(checkInventory = true){
if (checkInventory) {}
....
}
在这种情况下,您要为checkInventory
参数分配默认的true
值。 因此,您可以调用getFruits
方法而无需传递checkInventory
参数: getFruits()
。 这与getFruits(true)
相同。 如果未将任何值传递给此参数,则编译器将使用方法声明中定义的默认值true
。
您仍然可以将任何类型的另一个值传递给checkInventory
参数,因为它隐式定义为any
类型,例如getFruits(123)
或getFruits("apple")
但是另一个呢?
getFruits(checkInventory: boolean){
if (checkInventory) {}
....
}
您正在定义checkInventory
参数的类型,而不是其值。 现在,您只能将boolean
值传递给checkInventory
参数(您仍然可以将null
或undefined
或any
类型的对象传递给此参数)。
您必须将任何boolean
值传递给getFruits
方法,如getFruits(true)
或getFruits(false)
。 如果使用getFruits()
或getFruits('apple')
则编译器将显示错误。
但是,如果您仍然尝试传递字符串或不提供任何值,则您的应用程序仍将运行,而不会出现任何编译错误。 TypeScript只是为JavaScript提供静态类型检查,而JavaScript变量可以是任何类型的任何类型。
请注意,当您的应用运行且您的传递值无法按预期读取或执行时,可能会发生错误。
您可以这样调用的第一个版本: getFruits()
。 这等效于getFruits(false)
。
对于第二个版本,编译器将存在,您需要显式传递一个checkInventory
值。
对于
getFruits(checkInventory = true){
if (checkInventory) {}
....
}
您正在设置checkInventory
的默认值
因此, checkInventory()
与checkInventory(true)
相同。 当然,您可以通过传递另一个值checkInventory(true)
来覆盖该值。
但是,在这种情况下,未定义参数类型,默认为any
。 因此,您可以使用任何类型的参数来调用该函数。 checkInventory("string")
。
对于
getFruits(checkInventory: boolean){
if (checkInventory) {}
....
}
您正在定义参数的类型。 它必须是true
还是false
。 这种情况下没有默认值。
如果尝试像checkInventory("string")
一样调用此函数,则编译器将引发错误,因为它期望使用boolean
类型,但会得到string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.