使用reduce函数返回结果会产生类型错误,但是将结果保存在变量(isValid
)中然后返回该变量不会产生任何错误。
由于这两种方法在语义上是等价的,因此我想知道这是否是TS类型推断系统中的一个错误。
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;
};