[英]Why does typescript accept a number value as a type?
I had a bug in my Angular 4 project where I had declared a variable: 我在Angular 4项目中声明一个变量时遇到了一个错误:
debounce: 300;
instead of 代替
debounce = 300;
So of course this.debounce was undefined before the fix. 因此,当然,在修复之前,this.debounce是未定义的。
Shouldn't typescript give me an error in this case? 在这种情况下,打字稿不应该给我一个错误吗?
If you declare a variable with a type annotation of 300
, that means not only is the type numeric, but only the value 300
is acceptable: 如果声明类型注释为
300
的变量,则不仅意味着数字类型,而且仅可接受值300
:
var debounce: 300;
You will get an error if you attempt to assign, say, 200: 如果您尝试分配例如200,则会出现错误:
debounce = 200;
Switch on strict null checks, and the compiler will catch this kind of problem (you meant to assign the value, not a type annotation): 启用严格的空检查,编译器将捕获这种问题(您打算分配值,而不是类型注释):
var debounce: 200;
// Strict null checks tells you here that you have done something strange
var x = debounce;
In this case, when you try to use the variable, strict null checks points out you never assigned a value - thus telling you that you made an annotation, not an assignment. 在这种情况下,当您尝试使用该变量时,严格的null检查会指出您从未分配值-从而告诉您进行注释而不是分配。
You can basically pass (almost) anything as a value type to Typescript. 您基本上可以将(几乎)任何东西作为值类型传递给Typescript。 So if you say:
因此,如果您说:
class SomeClass {
debounce: 300 | 500 | 700;
constructor() {
this.debounce = 400;
}
}
You will get a type error, since typescript is expecting the value for debounce to be 300
, 500
or 700
, not just any number. 你会得到一个类型的错误,因为打字稿期待值的防抖动是
300
, 500
或700
,不是任何数字。 This means that you can be more specific about type annotations. 这意味着您可以更详细地了解类型注释。
That line is correct because unintentionally you have used literal-types
( for more information ): 该行是正确的,因为您无意中使用了
literal-types
( 有关更多信息 ):
This example helps you to understand how literal-types
is used for restricting variables to a finite set of possible values : 此示例可帮助您了解如何使用
literal-types
将变量限制为一组有限的可能值 :
let zeroOrOne: 0 | 1;
zeroOrOne = 0;
// OK
zeroOrOne = 1;
// OK
zeroOrOne = 2;
// Error: Type '2' is not assignable to type '0 | 1'
It's not a constant declaration. 这不是一个常量声明。 You have thought declared a variable and assigned a value implicitly typed.
您以为声明了一个变量,并为其分配了一个隐式类型的值。 You are wrong.
你错了。 It's
number
type declaration that accepts specific values only. number
类型声明仅接受特定值。
debounce: 300;
and then assign it with 然后分配给
this.debounce = 300;
Typescript won't give you an error because it's syntactically correct, but runtime errors follows for undefined
variables. Typescript不会给您错误,因为它在语法上是正确的,但是
undefined
变量会导致运行时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.