[英]Type 'undefined' is not assignable to type 'number' .ts(2322)
I'm stuck in learning Typescript language and need some explanations.我一直在学习 Typescript 语言,需要一些解释。 The problem is that variable named as
this.value
is never assigned as undefined due isValid
function check it.问题是命名为
this.value
变量从未被分配为 undefined 由于isValid
函数检查它。 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;
}
}
As the value
in constructor is optional.因为构造函数中的
value
是可选的。 its type is number | undefined
它的类型是
number | undefined
number | undefined
, you need to cast it as number when you are assigning it: number | undefined
,您需要在分配时将其转换为数字:
this.value = isValid(value) ? value as number : -1 ;
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.因此,构造函数的类型检查器不知道
isValid
只会在n
是数字时返回 true。
You can either inline the code of isValid
into the constructor:您可以将
isValid
的代码内联到构造函数中:
constructor(value) {
this.value = value && value > 0 && value < 10 ? value : -1;
}
or extend the function signature of isValid
with a user defined type guard :或使用用户定义的类型保护扩展
isValid
的函数签名:
export function isValid(n: any): n is number {
return n && n > 0 && n < 10;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.