1.

What are union types in TypeScript?

Answer»

A union type is a special construct in TypeScript that INDICATES that a value can be one of several types. A vertical bar (|) separates these types.

Consider the FOLLOWING example where the variable value belongs to a union type consisting of strings and numbers. The value is initialized to string “Foo”. Because it can only be a string or a number, we can change it to a number later, and the TypeScript compiler doesn’t complain. 

let value: string | number = "Foo";value = 10; // Okay

However, if we try to set the value to a type not included in the union types, we get the following error. 

value = true; // Type 'boolean' is not ASSIGNABLE to type 'string | number'.(2322)

Union types allow you to create new types out of existing types. This removes a lot of BOILERPLATE CODE as you don’t have to create new classes and type hierarchies.  



Discussion

No Comment Found