Introduction
Union types let you say a value can be one of several types. This helps your program accept different kinds of data safely.
Union types let you say a value can be one of several types. This helps your program accept different kinds of data safely.
let variable: type1 | type2 | type3;The pipe symbol | means "or" between types.
You can combine as many types as you need using |.
let value: string | number; value = "hello"; value = 42;
function printId(id: number | string) { console.log(`ID: ${id}`); } printId(101); printId("202");
type Status = "success" | "error" | "loading"; let currentStatus: Status = "loading";
This program shows how union types let a function handle both strings and numbers safely by checking the type first.
function formatInput(input: string | number) { if (typeof input === "string") { return `Text: ${input.toUpperCase()}`; } else { return `Number: ${input.toFixed(2)}`; } } console.log(formatInput("hello")); console.log(formatInput(3.14159));
Use union types to make your code flexible but still safe.
Always check the type before using methods specific to one type.
Union types let variables hold multiple types.
They help functions accept different kinds of inputs.
They improve code safety by forcing type checks.
let value: string | number;string | number means the variable can hold either a string or a number.string or number in TypeScript?| to separate types.| correctly, while others use invalid syntax.function format(value: string | number) {
if (typeof value === 'string') {
return value.toUpperCase();
} else {
return value.toFixed(2);
}
}
console.log(format('hello'));
console.log(format(3.14159));toUpperCase() converts it to uppercase, so 'hello' becomes 'HELLO'.toFixed(2) formats it to 2 decimal places, so 3.14159 becomes '3.14'.function printLength(value: string | number) {
console.log(value.length);
}
printLength('test');
printLength(123);length on value is unsafe because numbers don't have a length property.value is a number.string or an Array<string> and returns the total number of characters. Which is the best way to use union types to achieve this?Pass the test and this pattern moves unknown