TypeScript: Union types
1 min read

TypeScript: Union types

The number variable above can be a number or a string. This type is called a union in TypeScript.  The union-type declaration could be done using the pipe (|) character.

If we have a string or number type we can use its specific methods and properties. For example we can use toFixed method on a number and toUpperCase method on a string.

On the Union type, we cannot directly use the specific methods on the constituent type.

One way to use the specific methods is to do assignment narrowing where the union type is given an explicit direct value as follows.

Another option is to use conditional narrowing.