【问题标题】:Adaptable function that can return undefined if input is undefined如果输入未定义,则可以返回未定义的自适应函数
【发布时间】:2021-04-07 19:34:18
【问题描述】:

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

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

【问题讨论】:

    标签: typescript undefined typescript-generics


    【解决方案1】:

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

    【讨论】:

    • 不错!也可以用定义为const f = (a: A)=>B…的函数来完成吗?
    猜你喜欢
    • 2016-11-04
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2020-11-28
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多