21

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.

0

2 Answers 2

27

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);
4
  • Is this true for typescript? I mean when typescript compile the code, not assigned any default value?
    – OmG
    Commented Jun 9, 2017 at 2:49
  • @OmG Compile some code and see for yourself. TypeScript is merely a type layer on top of JS, and a transpiler. It does not change the meaning of the code, or introduce any of its own semantics.
    – user663031
    Commented Jun 9, 2017 at 2:56
  • Yes, it's true for typescript. I'll add an example to the answer for you.
    – Bumpy
    Commented Jun 9, 2017 at 3:05
  • Thankyou @torazaburo for fixing up the hash I made of my original answer.
    – Bumpy
    Commented Jun 9, 2017 at 12:49
5

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.

1
  • In recent versions of typescript I have seen that you can not assign 'unassigned' to a string variable. how can this be ? Commented Mar 13, 2022 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.