[英]typeof result, when stored in a variable, is not longer used by TS for type inference
consider the following code:考虑以下代码:
export const func = (foo?: number) => {
const isNumber = typeof foo === 'number';
return isNumber ? Math.max(foo, 0) : 0;
};
Here, TS complains that undefined
cannot be applied to Math.max
.在这里,TS 抱怨
undefined
不能应用于Math.max
。 On the other hand, this works just fine:另一方面,这很好用:
export const func = (foo?: number) => {
return typeof foo === 'number' ? Math.max(foo, 0) : 0;
};
Can somebody explain why this is ?有人可以解释为什么会这样吗?
Thanks谢谢
Refactoring an expression to create a new variable (or const) like this often doesn't give you the same results from the type-checker, because Typescript infers a type for your variable and then uses that type subsequently, and the type it infers may be different from what would be inferred for the same expression in its original context.重构表达式以创建像这样的新变量(或常量)通常不会从类型检查器中给您相同的结果,因为 Typescript 会为您的变量推断一个类型,然后随后使用该类型,而它推断的类型可能与在其原始上下文中为同一表达式推断的内容不同。
In this case, the type of isNumber
is just boolean
;在这种情况下,
isNumber
的类型只是boolean
; this type has no relationship to the variable foo
so a conditional expression on it doesn't narrow the type of the different variable foo
.此类型与变量
foo
没有关系,因此对它的条件表达式不会缩小不同变量foo
的类型。 In the original code, however, it is more like a type guard of the form foo is number
, which is a subtype of boolean
.然而,在原始代码中,它更像是
foo is number
形式的类型保护,它是boolean
的子类型。 A type guard can be used as a type annotation for a function, but not as the type of a variable.类型保护可以用作函数的类型注释,但不能用作变量的类型。
To be able to verify code like your example, Typescript would have to keep track not just of the types of variables, but also the relationships between types of multiple variables;为了能够像您的示例一样验证代码,Typescript 不仅要跟踪变量的类型,还要跟踪多个变量类型之间的关系; instead of inferring
isNumber: boolean
it would have to infer something like:而不是推断
isNumber: boolean
它必须推断如下:
foo: number
and isNumber: true
, or foo: undefined
and isNumber: false
" . foo: number
和isNumber: true
,要么是foo: undefined
和isNumber: false
” 。 Inferring types like this would be messy, complicated, and the complexity of the types would grow exponentially in the number of variables.像这样推断类型将是混乱、复杂的,并且类型的复杂性会随着变量的数量呈指数增长。
More generally, Typescript's type checker does not prove every provable fact about your code, and doesn't try to.更一般地说,Typescript 的类型检查器不会证明关于您的代码的每一个可证明的事实,也不会尝试这样做。 It has a set of rules which it follows to infer and narrow types, but this set of rules is not a complete logical system .
它有一套规则来推断和缩小类型,但这一套规则并不是一个完整的逻辑系统。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.