【问题标题】:Typescript: Why can there be several function declarations without function bodies?Typescript:为什么可以有多个没有函数体的函数声明?
【发布时间】:2020-08-12 13:39:17
【问题描述】:
我在this GitHub issue of the react-navigation library 中找到了以下 Typescript 代码,其中一个接一个地有几个函数声明,但只有最后一个声明包含函数体:
export function navigate(
route:
| { key: string; params?: object }
| { name: string; key?: string; params?: object }
): Action;
export function navigate(name: string, params?: object): Action;
export function navigate(...args: any): Action {
if (typeof args[0] === 'string') {
// implementation details...
} else {
// implementation details...
}
}
这是如何工作的?
【问题讨论】:
标签:
typescript
function
overloading
react-navigation
【解决方案1】:
这是一个名为 函数重载 的 Typescript 功能,即nicely explained here。
如果您的参数类型包含条件运算符(如联合类型|),您可以使用它来避免运行时错误。
如果你只有一个包含函数体的函数声明(而不是其他两个没有函数体的声明),那将是一件危险的事情,因为any 将允许在编译时进行任何操作,并且只在运行时你' d 根据发生的 if/else 情况而遇到错误:
export function navigate(...args: any): Action {
if (typeof args[0] === 'string') {
// implementation details...
} else {
// implementation details...
}
}
很明显,如果开发人员没有其他两个函数声明,她/他可能不会使用any。但是在example of Dr. Axel Rauschmayer 中,您会发现如果将条件作为参数而不是...args: any 添加甚至会出现问题,事实上:
export function navigate(
nameOrRoute:
| string
| { key: string; params?: object }
| { name: string; key?: string; params?: object },
params?: object
): any {
if (typeof nameOrRoute === 'string') {
// implementation details...
} else {
// implementation details...
}
}
这将允许在编译期间进行多种参数组合,但在运行时的某些情况下会导致错误。