简体   繁体   English

TypeScript 类型防护 function 在使用数组 reduce 时推断出错误的类型

[英]TypeScript type guard function infers wrong type when using array reduce

Returning the result of the reduce function gives a type error, but saving the result in a variable ( isValid ) and then returning the variable doesn't give any error.返回 reduce function 的结果会出现类型错误,但将结果保存在变量 ( isValid ) 中然后返回该变量不会出现任何错误。

Since both methods are semantically equivalent I wonder if this is a bug in TS type inference system.由于这两种方法在语义上是等价的,我想知道这是否是 TS 类型推理系统中的错误。

TypeScript Playground TypeScript 游乐场

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;
};

There are already a lot of issues regarding the type inference for reduce in TS Github, the one collecting them all is Array method definition revamp: Use case collection #36554在 TS Github 中已经有很多关于 reduce 的类型推断的问题,将它们全部收集起来的是Array method definition revamp: Use case collection #36554

I believe your method falls into the same error category as the one in 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
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM