TypeScript类型保护函数在使用数组reduce时推断错误的类型。

3

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

1个回答

3

在 TypeScript 的 Github 上,关于 reduce 方法类型推断的问题已经有很多讨论,其中一个收集这些问题的地方是 Array method definition revamp: Use case collection #36554

我认为你的方法跟这个 评论 中提到的那个错误类别一样。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接