typescript - 无法使用打字稿联合类型调用 Array.every()
问题描述
下面的代码在使用时会抛出错误Array.every()
// In my code, data it would be assigned from an API response;
let data: string[] | string[][] = [];
// Need to use every() and some() for checking
let isChecked = false;
// Check if the type is string[][], got error with every()
if (data.length && data[0] instanceof Array) {
isChecked = data.every(...);
}
// Check if the type is string[], no error with some()
if (data.length && typeof data[0] === 'string') {
isChecked = data.some(...);
}
打字稿将在以下位置显示此错误every()
:
Each member of the union type
'{ <S extends string>(predicate: (value: string, index: number, array: string[]) => value is S, thisArg?: any): this is S[];
(predicate: (value: string, index: number, array: string[]) => unknown, thisArg?: any): boolean; } | { ...; }'
has signatures, but none of those signatures are compatible with each other
我该如何克服这个错误。这是一个打字稿游乐场示例
解决方案
let a: string[] | string[][] = [];
const isArrOfArr = (arg: any): arg is string[][] => Array.isArray(arg) && Array.isArray(arg[0])
const isArrOfArr_super_safe = (arg: any): arg is string[][] => Array.isArray(arg) && arg.every(Array.isArray)
if (isArrOfArr(a)) {
let b = a.every(elem => elem) // ok
}
TS 不将data[0] instanceof Array
其视为第一个元素的类型保护,因为默认情况下数组是可变的。
您可以为此目的使用自己的 typeguard
推荐阅读
- telerik - 在 Jenkins 构建期间恢复 Telerik 的 nuget 包
- android - Android udp 服务器无法通过 SIM 卡(4G)接收数据
- nlp - word2vec 将similar_by_vector() 结果限制为重新训练的语料库
- html - 如何检查 HTML 文件是否在给定目录中,然后使用同一目录中引用的 CSS 和 JS 文件打开该文件
- google-chrome-extension - 如何在特定域的扩展中禁用 301 响应的缓存
- asp-classic - ASP Classic 循环中的逻辑语句
- node.js - 如何使用 mongoose 获取 MongoDB 数据库统计信息?
- c# - 对水平 ListView 进行排序
- javascript - 为什么必须使用函数表达式来定义构造函数内部的方法?
- ssl - vaultsharp tls 身份验证失败 - 必须提供客户端证书