【问题标题】:TypeScript type guard function infers wrong type when using array reduceTypeScript 类型保护函数在使用数组 reduce 时推断出错误的类型
【发布时间】:2021-10-21 23:14:43
【问题描述】:

返回 reduce 函数的结果会产生类型错误,但将结果保存在变量 (isValid) 中然后返回变量不会产生任何错误。

由于这两种方法在语义上是等效的,我想知道这是否是 TS 类型推断系统中的错误。

TypeScript Playground

interface Params {
    a: string;
    b: number;
}

const paramKeys = ["a", "b"] as const;

// Doesn't work -> Type 'string' is not assignable to type 'boolean'.
const isHydrationParamsValid = (params: any): params is Params => {
    return paramKeys.reduce((_, curr) => {
        if (!params[curr]) {
            console.warn(`Hydration param ${curr} is missing`);
            return false;
        }
        return true;
    }, true);
};

// Works!
const isHydrationParamsValid2 = (params: any): params is Params => {
    const isValid = paramKeys.reduce((_, curr) => {
        if (!params[curr]) {
            console.warn(`Hydration param ${curr} is missing`);
            return false;
        }
        return true;
    }, true);
    return isValid;
};

【问题讨论】:

    标签: typescript typeguards


    【解决方案1】:

    TS Github中关于reduce的类型推断已经有很多问题了,收集到的就是Array method definition revamp: Use case collection #36554

    我相信您的方法与comment 中的方法属于同一错误类别:

    // the return type here is correctly inferred as `boolean`
    function works() {
      return new Array('foo', 'bar').reduce(
        (previousValue, currentValue) => !!(previousValue && currentValue),
        true
      )
    }
    
    function broken(): boolean {
      return new Array('foo', 'bar').reduce(
        (previousValue, currentValue) => !!(previousValue && currentValue),
        true
      )
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 2021-12-21
      • 2018-08-28
      • 2013-05-10
      • 2020-01-24
      • 1970-01-01
      相关资源
      最近更新 更多