最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Type 'undefined' is not assignable to type 'number' .ts(2322) - Stack Overflow

programmeradmin6浏览0评论

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 ;
发布评论

评论列表(0)

  1. 暂无评论