简体   繁体   中英

How to narrow custom number type by if condition in typescript

Code

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)
}

In this situation, typescript show error Argument of type 'number' is not assignable to parameter of type 'FingerType'

How to make typescript compiler ensure that digit is FingerType ?

A common way to solve this would be to use a type guard .

const isFingerType = (n: number): n is FingerType => 0 < digit && digit < 6

const digit = Math.floor(Math.random() * 10);
if (isFingerType(digit)) {
    fingerFn(digit)
}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM