Complete the code to declare a variable that can hold a string or a number.
let value: [1];The union type syntax uses the pipe | to allow a variable to hold one of multiple types.
Complete the function parameter type to accept either a string or an array of strings.
function printNames(names: [1]) { if (typeof names === 'string') { console.log(names); } else { names.forEach(name => console.log(name)); } }
The parameter can be either a string or an array of strings, so we use the union type string | string[].
Fix the error in the union type declaration for the variable.
let data: [1] = 42;
The union type should use the pipe | to allow data to be either a number or a string.
Fill both blanks to create a union type and check the type inside the function.
function process(input: [1]) { if (typeof input === [2]) { console.log('Input is a string:', input); } }
typeof against a type name without quotes.The parameter input can be a string or number, so use string | number. The typeof check for a string uses the string literal 'string'.
Fill all three blanks to create a union type, check the type, and handle both cases.
function format(value: [1]) { switch (typeof value) { case [2]: return value.toUpperCase(); case [3]: return value.toFixed(2); } }
The parameter value can be a string or number. The typeof checks use string literals 'string' and 'number'. The function handles both cases accordingly.