You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中通过if条件收窄自定义数字类型?

TypeScript类型匹配问题解决

问题代码

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编译器确认digit属于FingerType类型:

1. 类型断言

当你已经通过逻辑判断确认digit的范围符合FingerType时,直接用类型断言告知编译器:

if (0 < digit && digit < 6) {
    fingerFn(digit as FingerType)
}

2. 自定义类型守卫

如果需要更严谨的类型校验,可编写类型守卫函数,让编译器通过函数返回值自动推断类型:

type FingerType = 1 | 2 | 3 | 4 | 5;

function isFingerType(num: number): num is FingerType {
    return num >= 1 && num <= 5;
}

function fingerFn(finger: FingerType) {
    console.log("finger : ", finger);
}

const digit = Math.floor(Math.random() * 10);
if (isFingerType(digit)) {
    fingerFn(digit); // 此处digit会被TypeScript推断为FingerType
}

3. 枚举式条件判断

直接在条件中列出FingerType的所有可能值,让编译器精准缩小类型范围:

const digit = Math.floor(Math.random() * 10);
if (digit === 1 || digit === 2 || digit === 3 || digit === 4 || digit === 5) {
    fingerFn(digit);
}

这种方式无需额外语法,通过明确的条件让编译器完全确定digit的取值属于目标类型。

内容的提问来源于stack exchange,提问作者Byeongin Yoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:26:16