[英]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: Output:
Example is String Array undefined
I have given the var type as a "number" , but why the output screen shows "String array" ?我已将 var 类型指定为“数字” ,但为什么 output 屏幕显示“字符串数组” ?
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.您没有给变量example
赋值,因此默认情况下它是undefined
,这就是您的代码运行最后一个else
语句的原因。
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.即使您刚刚声明了一个数字变量,但您没有为该变量分配一个数字,因为我们非常清楚我们在 typescript 中没有任何数字的默认值这将是未定义的,并且您为变量不是该变量的属性它将是分配给该变量的值的属性。
pass a number in the function instead of an example variable(that doesn't hold a value), y it shows string array as type?在 function 中传递一个数字而不是示例变量(不包含值),它显示字符串数组作为类型? bcz when its undefined, the typeof undefined doesn't match with string or number, hence it goes to the else block. bcz 未定义时,未定义的类型与字符串或数字不匹配,因此它转到 else 块。
In TypeScript, indeed we can assign the "type" to a variable at the start;在 TypeScript 中,确实可以在开始时将“类型”分配给变量; 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
.但是,众所周知,最终 TypeScript 文件将转换为 JavaScript (以便我们的浏览器可以理解并对其进行处理),并且分配给未分配任何值的变量的默认值是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
.行分配变量类型但不将值分配给变量 example ,因此它在执行时获取undefined
并输入最后一个 else 条件并打印: Example is String Array undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.