TypeScript 无法将您的 .every 调用理解为类型保护。您可以为此编写自己的type guard/predicate,尽管这不是必需的。 .every 的类型有两个重载,一个是实际谓词:
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): this is S[];
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns a value
* which is coercible to the Boolean value false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
要使用类型保护重载版本,您传递给.every 的谓词本身必须是类型保护。您可以简单地向数组函数添加一个返回类型,将其标记为类型保护:
function _addDataAtIndex(
totalData: Array<string | string[]>,
dataToAdd: Array<Array<string | string[]>>,
addIndex: number,
) {
dataToAdd.forEach((dataArr) => {
// Note the `: x is string` here
if (dataArr.every((x): x is string => typeof x === 'string')) {
// each value is a string - insert the entire array
totalData.splice(addIndex, 0, dataArr);
} else {
totalData.splice(addIndex, 0, dataArr[0]);
}
});
}
现在它使用 .every 的类型保护版本,这使得 TypeScript 意识到 dataArr 是 if 语句分支中的 string[]。