Home > Net >  How to narrow custom number type by if condition in typescript
How to narrow custom number type by if condition in typescript

Time:09-13

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 ?

CodePudding user response:

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

  • Related