TypeScript Union Types
A union type is used when a value can be more than one type.
For example, a property might hold either a string or a number.
Union | (OR)
The | symbol means "or". Writing string | number says the parameter is a string or a number.
Example
Both the number 404 and the string '404' are accepted by the same function.
Prompt
Show a parameter that accepts either a string or a number using a union type.
Write a function
printStatusCode whose code parameter is typed string | number and logs "My status code is ." in a template string, then call it once with the number 404 and once with the string '404'.
Output: TypeScript file and captured output
script.ts
function printStatusCode(code: string | number) {
console.log(`My status code is ${code}.`)
}
printStatusCode(404);
printStatusCode('404');
Union Type Errors
Note: When you use a union type, you need to know which type you actually have before using type-specific features, or you get type errors.
Example
Calling toUpperCase() fails here: it is a string method, and a number does not have it, so TypeScript rejects the call on string | number.
Prompt
Show the compile error you get when calling a string-only method on a union-typed value.
Write a function
printStatusCode with a code: string | number parameter that logs code.toUpperCase() inside a template string; the compiler must report that toUpperCase does not exist on type string | number because number has no such method.
Output: TypeScript file and captured output
script.ts
function printStatusCode(code: string | number) {
console.log(`My status code is ${code.toUpperCase()}.`) // error: Property 'toUpperCase' does not exist on type 'string | number'. Property 'toUpperCase' does not exist on type 'number'
}