Skip to main content

Union

Union Type

//age can be both a number and a string
let age: number | string;
age=23;
age="24";
Union Type in a function
const printAge=(age:number|string)=>{
console.log('You are ${age} years old' );
}

Type narrowing

//we can start with user input that can be a string and narrow it to a number
const calculateTax = (price:number|string,tax:number) =>{
if(typeof price === "string"){
price = parseFloat(price.replace("$",""));
}
return price * tax;
}

Array of different types

//create an array of type number or string
const stuff:(number|string)[];
stuff.push("test");
stuff.push(111);

Literal type

//literal types are the value themselves
const giveAnswer = (answer:'yes'|'no'|'maybe') =>{
return `The answer is ${answer}`;
}
giveAnswer('no');