Curriculum
Course: TypeScript
Login
Text lesson

TS Union Types

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.

Union | (OR)

By using the | operator, we indicate that our parameter can be either a string or a number.

Example

function printStatusCode(code: string | number) {
  console.log(`My status code is ${code}.`)
}
printStatusCode(404);
printStatusCode(‘404’);

Union Type Errors

Note: When using union types, it’s important to be aware of the specific type to avoid type errors.

Example

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.