Consider a function that accepts either a string or a number. Why are union types useful in this case?
Think about how TypeScript helps you write safer code when a variable can be more than one type.
Union types let you specify that a value can be one of several types. This helps the compiler check your code and catch errors early, while still allowing flexibility.
What is the output of this TypeScript code?
function formatInput(input: string | number): string { if (typeof input === 'number') { return `Number: ${input.toFixed(2)}`; } else { return `String: ${input.toUpperCase()}`; } } console.log(formatInput(3.14159)); console.log(formatInput('hello'));
Look at how the function treats numbers and strings differently.
The function checks the type of input. For numbers, it formats to 2 decimals. For strings, it converts to uppercase.
What error does this TypeScript code produce?
function process(value: string | number) { return value.toFixed(2); } process('test');
Think about which types have the method toFixed.
The method toFixed exists only on numbers. Since value can be a string, TypeScript raises an error.
Which option shows the correct way to declare a variable that can be a string or null?
Union types use a specific symbol between types.
The pipe symbol | is used to declare union types in TypeScript.
Given this function, what will be the value of result after calling combine(5, ' apples')?
function combine(a: number | string, b: number | string): string { if (typeof a === 'number' && typeof b === 'string') { return a + b; } else if (typeof a === 'string' && typeof b === 'number') { return a + b.toString(); } else { return 'Invalid input'; } } const result = combine(5, ' apples');
Check the types of a and b and which condition matches.
Since a is a number and b is a string, the first condition is true and the function returns their concatenation.