Union types are used when a value can be one of several specified types, such as a property that could be either a string or a number.
By using the | operator, we indicate that our parameter can be either a string or a number.
function printStatusCode(code: string | number) { console.log(`My status code is ${code}.`) } printStatusCode(404); printStatusCode(‘404’); |
Note: When using union types, it’s important to be aware of the specific type to avoid type errors.
function printStatusCode(code: string | number) { console.log(`My status code is ${code.toUpperCase()}.`) // error: Property ‘toUpperCase’ does not exist ontype ‘string | number’. Property ‘toUpperCase’ does not exist on type ‘number’ } |
In our example, we encounter an issue with invoking toUpperCase() because it’s a method specific to strings, and the number type does not have this method.