代码之家  ›  专栏  ›  技术社区  ›  dumbmatter

可以返回多个不同对象的函数的返回类型的更好的TypeScript推断

  •  1
  • dumbmatter  · 技术社区  · 5 年前

    我有这样一个函数:

    function foo() {
        if (Math.random() < 0.5) {
            return {
                a: 5
            };
        }
    
        return {
            b: false
        };
    }
    

    function foo(): {
        a: number;
        b?: undefined;
    } | {
        b: boolean;
        a?: undefined;
    }
    

    就我的目的而言,最好是将其推断为:

    function foo(): {
        a: number;
    } | {
        b: boolean;
    }
    

    我知道我可以通过在 foo . 但我问这个问题是因为实际上我有一个函数,它的返回值要复杂得多,我不想手工编写返回值的类型,然后永远保持同步。

    有没有办法让TypeScript像我希望的那样自动推断返回类型?

    2 回复  |  直到 5 年前
        1
  •  2
  •   Alexey Lebedev    5 年前

    奇怪的是,如果您首先将返回值赋给临时变量,那么返回类型就是您所期望的:

    function foo() {
        if (Math.random() > 0.5) {
            const ret = { a: 5 };
            return ret;
        } else { 
            const ret = { b: false };
            return ret;
        }
    }
    
        2
  •  1
  •   Ali Habibzadeh    5 年前

    缩小范围并通过将返回类型存储在const中来帮助Ts,let。

    function foo() {
      const isInRage = Math.random() < 0.5;
      const inRageResults = { a: 5 };
      const outOfRangeResults = { b: false };
      return isInRage ? inRageResults : outOfRangeResults;
    }
    

    {
        a: number;
    } | {
        b: boolean;
    }
    
    推荐文章