Sintaxis:
1 | type1|type2|type3 |
Ejemplo 1: Variable de tipo de unión:
1 2 3 4 5 | var val:string|number //this variable can has type string or number val = 1986 console.log( "numeric value of val " +val) val = "This is a string" console.log( "string value of val " +val) |
Resultado:
1 2 | [LOG]: numeric value of val 1986 [LOG]: string value of val This is a string |
Ejemplo 2: Tipo de unión y parámetro de función
1 2 3 4 5 6 7 8 9 | function sum(values:string|number[]):number{ if ( typeof values == "string" ){ return values.split( "," ).map(parseFloat).reduce((a,b)=>(a+b)) } else { return values.reduce((a,b)=>(a+b)) } } console.log(sum([1,2])) console.log(sum( "1,2" )) |
Resultado:
1 2 | [LOG]: 3 [LOG]: 3 |
Ejemplo 3: tipo de unión y matriz
1 2 3 4 5 | var arr:string[]|number[] arr = [1990,1986] console.log( "numeric values of arr " +arr) arr = [ "tutorialspots" , ".com" ] console.log( "string values of arr " +arr) |
Resultado:
1 2 | [LOG]: numeric values of arr 1990,1986 [LOG]: string values of arr tutorialspots,.com |
0 Comentarios
Dejanos tu comentario para seguir mejorando!