TypeScript Types

Union types — alternative value shapes

A union describes values assignable to at least one member type. A value with a union annotation can only be used in ways that are safe for the possibilities that remain after narrowing. A discriminant or primitive guard can establish a more specific member. A union is not a runtime tag or automatically a set of mutually exclusive object shapes. Example output: "12.0". The example was designed for strict checking with an ES2022 target; type annotations do not add runtime validation.

Formal Syntax & Structure

typescript syntaxtypescript
type Result = A | B;

Working Example

Example Snippettypescript
function show(value: string | number): string {  return typeof value === "string" ? value.toUpperCase() : value.toFixed(1);}console.log(show(12));
TypeScript Reference