Web Technologies - TypeScript

Back to Course

Lesson Description

Lession - #1449 TypeScript Union Type

In TypeScript, a union type variable is a variable which can store multiple type of values( i.e. number, string etc>
. A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe('|'>
symbol between the types. The union types help in some special situations

Union types are used when a value can be more than a single type.

Such as when a property would be string or number.


Union|( OR>

Using the | we're saying our parameter is a string or number


function printStatusCode( code string| number>
{ console.log( My status code is${ code}.>
printStatusCode( 404>
; printStatusCode(' 404'>
; Union Type Errors

Note you need to know what your type is when union types are being used to avoid type errors


function printStatusCode( code string| number>
{ ( My status code is${code.toUpperCase(>
// error Property' toUpperCase' doesn't exist ontype' string| number'. Property' toUpperCase' doesn't exist on type' number'

In our illustration we're having an issue invoking toUpperCase(>
as its a string method and number does not have access to it.

Online compiler