为何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
相关产品推荐
相关产品推荐

