Typescript中如何处理稀疏数组和undefined?
How to deal with sparse arrays and undefined in Typescript?
我目前有一个带有“孔”的稀疏数组。考虑:
let arr: number[] = []
arr[2] = 5
// arr = [,,5]
我正在使用第二个数组查找数组中的索引,如下所示:
let indices: number[] = [1, 2]
console.log(
indices.map(i => arr[i])
.includes(undefined)
)
// Expected output: true
但是,我得到这个错误:Argument of type 'undefined' is not assignable to parameter of type 'number'.
我认为这是因为 Typescript 认为 arr
只能包含数字,而实际上数组中的“空洞”计算为 undefined
。尽管 arr[1] === undefined
.
我可以使用 number | undefined
的联合类型来解决这个问题,但是有更好的方法吗?
来自 Javascript,我对 Typescript 还是比较陌生。
您可以使用 some
而不是 includes
indices.map(i => arr[i]).some(x => x === undefined)
我目前有一个带有“孔”的稀疏数组。考虑:
let arr: number[] = []
arr[2] = 5
// arr = [,,5]
我正在使用第二个数组查找数组中的索引,如下所示:
let indices: number[] = [1, 2]
console.log(
indices.map(i => arr[i])
.includes(undefined)
)
// Expected output: true
但是,我得到这个错误:Argument of type 'undefined' is not assignable to parameter of type 'number'.
我认为这是因为 Typescript 认为 arr
只能包含数字,而实际上数组中的“空洞”计算为 undefined
。尽管 arr[1] === undefined
.
我可以使用 number | undefined
的联合类型来解决这个问题,但是有更好的方法吗?
来自 Javascript,我对 Typescript 还是比较陌生。
您可以使用 some
includes
indices.map(i => arr[i]).some(x => x === undefined)