You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何参数不兼容的函数类型联合等价于接收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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:45:59