简体   繁体   中英

Why the output is a string array even after assigning the variable as number in typescript?

Code:

function fun(example:string|number|string[])
{
    if(typeof example == "string")
    {
        console.log("Example is String " + example);
    }
    else if(typeof example == "number")
    {
        console.log("Example is Number " + example);
    }
    else{
        console.log("Example is String Array " + example);
    }
}
var example:number; //Here i have assigned the var as a number
fun(example); 

Output:

Example is String Array undefined

I have given the var type as a "number" , but why the output screen shows "String array" ?

You haven't given a value to the variable example , hence by default it's undefined , that's why your code runs the last else statement.

Try with:

var example = 3
fun(example)
// Example is Number 3

Remember that type annotations are used at compile time. This means that when your code runs, it doesn't know anything about the types you declared.

Even though you just declared a number variable but you haven't assigned that variable a number, as we know very well we don't have any default value of the number in typescript It would be undefined and the property that you have defined for the variable is not the property of that variable It will be the property of the value that will be assigned to that veriable.

pass a number in the function instead of an example variable(that doesn't hold a value), y it shows string array as type? bcz when its undefined, the typeof undefined doesn't match with string or number, hence it goes to the else block.

In TypeScript, indeed we can assign the "type" to a variable at the start; however, as we all know that ultimately a TypeScript file gets converted into the JavaScript (so that our browser can understand and work over that) and the default value assigned to a variable which hasn't assigned any value is undefined .

var example:number; line assigns the variable type but doesn't assigns the value to variable example and hence it gets the undefined at execution time and enters the last else condition and prints: Example is String Array undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM