Reputation: 18838
Where can I find the default value of each type in typescript? For example, where is mentioned the default value for number
type is null
or 0.
? Or about the string
?
The default value means the value of a variable that is defined, but not assigned. Like let a : number;
. This happens a lot in object definitions. For example:
class A{
let a: number;
let b: string;
}
let obj: A;
Therefore, the question is on the values of a
and b
for obj
.
Upvotes: 22
Views: 72767
Reputation: 8552
You have to remember that Typescript transpiles to javascript. In Javascript, the default value of an unassigned variable is undefined
, as defined here.
For example, the following typescript code:
let a: string; console.log(a);
will transpile to the following javascript and logs 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:
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.
Upvotes: 5
Reputation: 1342
The default value of every type is undefined
From: MDN - 'undefined'
A variable that has not been assigned a value is of type undefined.
For example, invoking the following will alert the value 'undefined', even though greeting
is of type String
let greeting: string;
alert(greeting);
Upvotes: 28