typescript - 通过映射中数组的索引区分类型
问题描述
打字稿中有没有办法使用正确类型的地图访问元素?以下会引发错误,因为 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"
}
})
解决方案
如果你确定你的元组只有两种字符串和数字类型,你可以typeof
这样使用:
y.map((el, i) => {
if (typeof el === 'number'){
el + 3
} else {
el + "pear"
}
})
推荐阅读
- node.js - NodeJS v12 重新启用 TLS 1.1 和 1.0
- reactjs - 当父组件在 Next.js 应用程序中更新其道具时重新渲染 React 子组件
- node.js - 如何使用 next 在 AWS S3 上托管静态文件?
- regex - 如何在 Notepad++ 中用正则表达式替换每一个奇数出现的子字符串?
- git - Git 有标签吗?
- python - 如何检测“节奏游戏”自动播放器的符号
- android - 当我更新它的版本时,Firebase auth 移动验证停止工作
- python - 如何使我的箭袋图更能代表数据,即。有明确的箭头?
- javascript - 使用切换按钮更新存储值
- angular - 具有多个子步骤的角步进器