Describe Union Types in TypeScript

Instruction: Explain the concept of union types in TypeScript and provide an example.

Context: This question tests the candidate's understanding of union types and their ability to illustrate how union types allow variables to store values of different types, enhancing code flexibility.

Official answer available

Preview the opening of the answer, then unlock the full walkthrough.

To clarify, Union Types are denoted by using the pipe (|) symbol between the types that a variable can hold. This notation is both straightforward to read and write, making the code easily understandable. For instance, consider a situation where a function parameter could either be a number or a string. In a traditional statically typed language without union types, this would require either overloading the function or using a less safe, common supertype. However, with TypeScript's Union Types, we can succinctly express this concept.

Let's delve into a practical example to illustrate this point further. Imagine we're developing a function named logId that is designed to accept either a number or...

Related Questions