raziEiL
raziEiL

Reputation: 87

Type 'undefined' is not assignable to type 'number' .ts(2322)

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

Upvotes: 2

Views: 7529

Answers (2)

meriton
meriton

Reputation: 70564

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

Upvotes: 4

Aadil Mehraj
Aadil Mehraj

Reputation: 2614

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 ;

Upvotes: 3

Related Questions