如何通过typescript中的if条件缩小自定义数字类型



代码

type FingerType = 1 | 2 | 3 | 4 | 5;
function fingerFn(finger: FingerType) {
console.log("finger : ", finger);
}
const digit = Math.floor(Math.random() * 10);
if (0 < digit && digit < 6) {
fingerFn(digit)
}

在这种情况下,typescript显示错误Argument of type 'number' is not assignable to parameter of type 'FingerType'

如何使typescript编译器确保digitFingerType

解决此问题的常用方法是使用类型保护。

const isFingerType = (n: number): n is FingerType => 0 < digit && digit < 6
const digit = Math.floor(Math.random() * 10);
if (isFingerType(digit)) {
fingerFn(digit)
}

游乐场

最新更新