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

为何TypeScript认为`(s: string, n: number) => (s || undefined) && n`会返回空字符串?

TypeScript 5.6.2中逻辑运算符组合的类型推断偏差问题

我正在编写一个输入为假值时返回undefined的函数,但在TypeScript 5.6.2中,以下写法无法通过类型检查:

// TypeScript推断返回类型:number | "" | undefined
const f1 = (s: string, n: number) => (s || undefined) && n;

// 报错:Type 'number | "" | undefined' is not assignable to type 'number | undefined'.
//   Type 'string' is not assignable to type 'number'.(2322)
const x: number | undefined = f1("a", 1);

TypeScript错误地推断f1的返回类型可能包含空字符串,但实际上这个返回值不可能存在——正确的返回类型应该是number | undefined。

交换参数位置后,会出现类似的类型推断问题:

// TypeScript推断返回类型:string | 0 | undefined
const f2 = (s: string, n: number) => (n || undefined) && s;

改用三元运算符或强制转换为布尔值的写法,就能让TypeScript正确推断返回类型:

// 返回类型:number | undefined
const f3 = (s: string, n: number) => (s ? true : undefined) && n;

// 返回类型:number | undefined
const f4 = (s: string, n: number) => (!!s || undefined) && n;

内容的提问来源于stack exchange,提问作者Kevin Chen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 18:12:39