Complete the code to declare a variable that can hold either a string or a number.
let value: [1];The | symbol creates a union type, allowing value to be either a string or a number.
Complete the function parameter type to accept either a string or an array of strings.
function greet(names: [1]) { if (typeof names === 'string') { console.log(`Hello, ${names}!`); } else { names.forEach(name => console.log(`Hello, ${name}!`)); } }
string[] which excludes single strings.& which is incorrect here.The parameter names can be either a single string or an array of strings, so we use a union type string | string[].
Fix the error in the type annotation to allow the variable to hold a number or null.
let result: [1] = null;& which causes a type error.Using | allows result to be either a number or null, which is needed here.
Fill both blanks to create a function that returns either a string or undefined based on input.
function getName(id: number): [1] { if (id === 1) { return 'Alice'; } return [2]; }
The function returns a string or undefined, so the return type is string | undefined and the return value for no match is undefined.
Fill all three blanks to create a variable that can hold a boolean, number, or string.
let data: [1] = true; data = 42; data = [2]; data = [3];
The variable data can hold boolean, number, or string. The union type is boolean | number | string. The values assigned are true, 42, 'hello', and false.