Union Types
When a value can be more than one type, use union types.
Union with or |
function logStatusCode(code: string | number) {
// type | type
console.log(`Status code: ${code}.`);
}
logStatusCode(404);
logStatusCode('404');
Union Type Errors
function logStatusCode2(code: string | number) {
console.log(`Status code: ${code.toUpperCase()}.`);
// error: Property 'toUpperCase' does not exist on type
// 'string | number'.
}