#8 Union Type (Advanced Types)
When we need a value that may be of either types like string or number, then we may use union type.
It can be written as;
function( weight: number | string ){
if(typeof weight === "number"){
return weight * 2;}
else{
return parseInt(weight)*2;}
Here, the weight may either be number or a string. To make the weight act as a number, we use IF where if the (type of weight === number) so that the weight can act as a number ELSE it shall act as a string.
Comments
Post a Comment