Typescript - null 和 undefined 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44536340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript - What is the difference between null and undefined?
提问by neomib
I want to know what is the difference between null and undefined in typescript. I know in javascript it is possible to use both of them in order to check a variable has no value. But in typescript I want to know the difference exactly and when it is better to use each one of them. Thanks.
我想知道打字稿中 null 和 undefined 之间有什么区别。我知道在 javascript 中可以同时使用它们来检查变量是否没有值。但是在打字稿中,我想确切地知道它们之间的区别以及何时最好使用它们中的每一个。谢谢。
采纳答案by Wernerson
This postexplains the differences very good. They are the same in Typescript as in Javascript.
这篇文章很好地解释了差异。它们在 Typescript 中与在 Javascript 中相同。
As for what you should use: The Typescript coding styleguide itselft states that you should always use undefined and not null: Typescript Styleguide
至于您应该使用什么:Typescript 编码样式指南本身指出您应该始终使用 undefined 而不是 null: Typescript Styleguide
回答by Subhasish Rath
The value 'undefined' denotes that a variable has been declared, but hasn't been assigned any value. So, the value of the variable is 'undefined'.
值 'undefined' 表示变量已声明,但尚未分配任何值。因此,变量的值是“未定义”。
On the other hand, 'null' refers to a non-existent object, which basically means 'empty' or 'nothing'.
另一方面,“null”指的是一个不存在的对象,这基本上意味着“空”或“什么都没有”。
You can manually assign the value 'undefined' to a variable, but that isn't recommended. So, 'null' is assigned to a variable to specify that the variable doesn't contain any value or is empty. But 'undefined' is used to check whether the variable has been assigned any value after declaration.
您可以手动将值 'undefined' 分配给变量,但不建议这样做。因此,将 'null' 分配给变量以指定该变量不包含任何值或为空。但是 'undefined' 用于检查变量在声明后是否被赋值。