【问题标题】:TS function return type inference with an optional parameter带有可选参数的 TS 函数返回类型推断
【发布时间】:2022-11-05 21:33:55
【问题描述】:
我认为一个例子是更好的解释方式。
const fn = (a: string, b?: string) => a || b;
const result = fn('', 'fallback'); //inferred type for `result` should be `string`, why it is `string | undefined`
如果我没有传递第二个参数(回退),我会理解的。
【问题讨论】:
标签:
typescript
string
function
optional-parameters
inferred-type
【解决方案1】:
TypeScript 的代码路径分析存在限制。
如果你想要你描述的结果,最简单的方法是函数重载:
function fn(a: string): string | undefined;
function fn(a: string, b: string): string;
function fn(a: string, b?: string): string | undefined {
return a || b;
}
const result1 = fn("", "fallback");
// ^? const result1: string
const result2 = fn("");
// ^? const result2: string | undefined
Playground example