How to use union in TypeScript

1 Answer

0 votes
let U: (string | number);
U = 123;   
U = "ABC"; 

function displayType(U: (string | number)) {
    if (typeof(U) === "number")
        console.log('number')
    else if (typeof(U) === "string")
            console.log('string')
}

displayType(123); 
displayType("ABC"); 
displayType(27184); 
displayType("TypeScript"); 

   
   
   
/*
   
run:
   
"number" 
"string" 
"number" 
"string" 
  
*/

 

 



answered Oct 24, 2021 by avibootz

Related questions

1 answer 91 views
1 answer 103 views
1 answer 140 views
2 answers 153 views
1 answer 154 views
1 answer 161 views
161 views asked Dec 27, 2020 by avibootz
1 answer 180 views
180 views asked Dec 11, 2020 by avibootz
...