如果输入未定义,则可返回未定义的自适应函数



如果有TypeScript函数f: A => B。然而,在我的应用程序中,输入可能是未定义的,所以我总是必须编写,比如const b?: B = a && f(a);

我可以更改函数以将检查包含在函数中吗(例如,类似(a: A | undefined) => B | undefined = (a => a && …),但类型化了,这样如果a不能未定义,返回类型就不包含未定义,这样我就可以写const b: B = f(a)(如果a不能不定义(和const b?: B = f(a)(如果a可以是?(?

这在函数重载的情况下是可行的:

// these are the two overloads
function f(x: number): string;
function f(x: number | undefined): string | undefined;
// this is the implementation, its type signature is not visible
function f(x: number | undefined): string | undefined {
return x?.toString();
}

使用这个问题的答案,它可以扩展到箭头函数:

const f: {
// these are the two overloads
(x: number): string;
(x: number | undefined): string | undefined;
} = 
// this is the implementation, its type signature is not visible
// not sure why arrow functions make typescript dumber but "any" is now necessary as the return type
(x: number | undefined): any => x?.toString();

最新更新