首页 > 解决方案 > 从数组中转移值的类型守卫

问题描述

const arr: number[] = []
const func = (n: number): void => {
    console.log(n)
}
arr.push(222)
if (arr.length > 0) {
    func(arr.shift())
}

我想func用一个数字作为参数来调用。但是,我在 IDE 中收到此错误消息:

'number | 类型的参数 undefined' 不能分配给“number”类型的参数。类型“未定义”不可分配给类型“数字”.ts(2345)

如何在不将参数形式设置为 的情况下解决此n: number问题n: number | undefined

标签: typescript

解决方案


推荐阅读