首页 > 解决方案 > 通过映射中数组的索引区分类型

问题描述

打字稿中有没有办法使用正确类型的地图访问元素?以下会引发错误,因为 map 中的类型是number | string

type Tuple = [number, number, string];

const y: Tuple = [1, 2, 'apple'];

y[0] // correctly typed as number
y[2] // correctly typed as string

y.map((el, i) => {

    if (i === y.length - 1) {
        el + 3
    } else {
        el + "pear"
    }
})

标签: typescript

解决方案


如果你确定你的元组只有两种字符串和数字类型,你可以typeof这样使用:

y.map((el, i) => {
    if (typeof el === 'number'){
       el + 3
    } else {
        el + "pear"
    }
})

PlaygorundLink


推荐阅读