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
2 Answers
Reset to default 4By 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
版权声明:本文标题:javascript - Type 'undefined' is not assignable to type 'number' .ts(2322) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744096275a2590339.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论