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.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

A union type describes a value that may belong to one of several types. Write alternatives with |. A parameter of type number | string accepts either, while an operation used without narrowing must be valid for both.

function formatId(id: number | string): string { if (typeof id === "number") return `number:${id.toString()}`; return `text:${id.toUpperCase()}`; } console.assert(formatId(0)...

Related Questions