为何参数不兼容的函数类型联合等价于接收never的函数?
TypeScript联合函数类型参数为何推断为never?
先看这段TypeScript代码:
type fnType = ((x: number) => void) | ((x: string) => void); const fn = (innerFn: fnType) => { innerFn("string"); }
执行时会触发错误:
Argument of type 'string' is not assignable to type 'never'
原因解析
核心是TypeScript对联合函数类型的调用规则:调用联合类型的函数时,传入的参数必须能被联合里的每一个函数分支都兼容。
具体到这段代码:
fnType是两个函数的联合:一个接受number类型参数,另一个接受string类型参数- 当调用
innerFn("string")时,这个参数需要同时满足能传给(x: number) => void和(x: string) => void - 但
string类型无法赋值给number类型,反过来number也不能赋值给string,两者的类型交集是空集,也就是never——没有任何类型能同时适配两个函数的参数要求,所以TypeScript就推断参数必须是never。
内容的提问来源于stack exchange,提问作者jhunter
相关产品推荐
相关产品推荐

