admin管理员组

文章数量:1394611

I'm stuck in learning Typescript language and need some explanations. The problem is that variable named as this.value is never assigned as undefined due isValid function check it. How to make typescript understand it?

export const isValid = (n: any) => n && n > 0 && n < 10;

class Test {
    value: number;
    constructor(value?: number) {
        /*
        Type 'number | undefined' is not assignable to type 'number'.
        Type 'undefined' is not assignable to type 'number'.ts(2322)
        */
        this.value = isValid(value) ? value : -1;
    }
}

I'm stuck in learning Typescript language and need some explanations. The problem is that variable named as this.value is never assigned as undefined due isValid function check it. How to make typescript understand it?

export const isValid = (n: any) => n && n > 0 && n < 10;

class Test {
    value: number;
    constructor(value?: number) {
        /*
        Type 'number | undefined' is not assignable to type 'number'.
        Type 'undefined' is not assignable to type 'number'.ts(2322)
        */
        this.value = isValid(value) ? value : -1;
    }
}
Share Improve this question asked Oct 28, 2020 at 4:55 raziEiLraziEiL 872 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

By default, the type checker does not look at the implementation of called functions, only their signature. Therefore, the typechecker for the constructor does not know that isValid will only return true if n is a number.

You can either inline the code of isValid into the constructor:

constructor(value) {
  this.value = value && value > 0 && value < 10 ? value : -1;
}

or extend the function signature of isValid with a user defined type guard:

export function isValid(n: any): n is number {
  return n && n > 0 && n < 10;
}

As the value in constructor is optional. its type is number | undefined, you need to cast it as number when you are assigning it:

 this.value = isValid(value) ? value as number : -1 ;

本文标签: javascriptType 39undefined39 is not assignable to type 39number39 ts(2322)Stack Overflow