typescript 打字稿中每种类型的默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44448411/
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
Default value for each type in typescript
提问by OmG
Where can I find the default value of each type in typescript? For example, where is mentioned the default value for numbertype is nullor 0.? Or about the string?
我在哪里可以找到打字稿中每种类型的默认值?例如,哪里提到numbertype的默认值是nullor 0.?或者关于string?
The default value means the value of a variable which is defined, but not assigned. Like let a : number;. This happens a lot in object definitions. For example:
默认值表示已定义但未分配的变量的值。喜欢let a : number;。这在对象定义中经常发生。例如:
class A{
let a: number;
let b: string;
}
let obj: A;
Therefore, the question is on the values of aand bfor obj.
因此,问题是对的价值观a和b对obj。
回答by Bumpy
The default value of every type is undefined
每种类型的默认值为 undefined
From: MDN - 'undefined'
来自:MDN - '未定义'
A variable that has not been assigned a value is of type undefined.
尚未赋值的变量的类型为 undefined。
For example, invoking the following will alert the value 'undefined', even though greetingis of type String
例如,调用以下将警告值“未定义”,即使greeting是类型String
let greeting: string;
alert(greeting);
回答by Mμ.
You have to remember that Typescript transpiles to javascript. In Javascript, the default value of an unassigned variable is undefined, as defined here.
您必须记住,Typescript 会转换为 javascript。在 Javascript 中,未赋值变量的默认值是undefined,如这里定义的。
For example, the following typescript code:
例如,以下打字稿代码:
let a: string; console.log(a);
will transpile to the following javascript and logs undefined.
将转换为以下 javascript 和日志undefined。
var a; console.log(a);
This also applies when you pass parameters to a function or a constructor of a class:
这也适用于将参数传递给类的函数或构造函数时:
// Typescript
function printStr(str: string) {
console.log(str);
}
class StrPrinter {
str: string;
constructor(str: string) {
this.str = str;
console.log(this.str);
}
}
printStr();
let strPrinter = StrPrinter();
In the code example above, typescript will complain that the function and the class constructor is missing a parameter. Nevertheless, it will still transpile to transpile to:
在上面的代码示例中,typescript 会抱怨函数和类构造函数缺少参数。尽管如此,它仍然会转译为:
function printStr(str) {
console.log(str);
}
var StrPrinter = (function () {
function StrPrinter(str) {
this.str = str;
console.log(this.str);
}
return StrPrinter;
}());
printStr();
var strPrinter = StrPrinter();
You might also want to see how typescript transpiles to javascript here.
您可能还想在此处查看 typescript 如何转换为 javascript 。

