如果输入未定义,可以 return 未定义的自适应函数

Adaptable function that can return undefined if input is undefined

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

我可以更改函数以在函数中包含检查(即类似 (a: A | undefined) => B | undefined = (a => a && …) 但键入时 return 类型不包含 undefined 如果 a 不能未定义,这样我可以写 const b: B = f(a) 如果 a 不能未定义, const b?: B = f(a) 如果可以吗?

这可以通过 function overloads:

// 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();
}

利用this question的答案,可以扩展为箭头函数:

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();