繁体   English   中英

Typescript函数默认参数分配和类型检查之间有什么区别?

[英]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参数(您仍然可以将nullundefinedany类型的对象传递给此参数)。

您必须将任何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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM