A union type allows a variable to hold values of different types by combining multiple types with the | symbol. For example, string | number means the variable can be a string or a number.
Click to reveal answer
beginner
How do you declare a variable that can be either a number or a boolean?
You use a union type like this: <code>let value: number | boolean;</code>. This means <code>value</code> can hold a number or a boolean.
Click to reveal answer
intermediate
What happens if you try to use a union type variable without checking its type first?
TypeScript will show an error if you try to use properties or methods that are not common to all types in the union. You need to check the type first to safely use specific features.
Click to reveal answer
intermediate
Explain how TypeScript narrows union types with an example.
TypeScript narrows union types by checking the type at runtime. For example:
if (typeof value === 'string') { // Here, value is treated as string console.log(value.toUpperCase()); } else { // Here, value is treated as number console.log(value.toFixed(2)); }
Click to reveal answer
beginner
Can union types include more than two types? Give an example.
Yes, union types can combine many types. For example: <code>let data: string | number | boolean;</code> means <code>data</code> can be a string, number, or boolean.
Click to reveal answer
Which symbol is used to create a union type in TypeScript?
A?
B&
C|
D:
✗ Incorrect
The pipe symbol | is used to combine types into a union.
What will TypeScript do if you try to call a method that exists only on one type in a union without checking the type first?
AAutomatically convert the type
BShow a type error
CIgnore the error
DRun the method anyway
✗ Incorrect
TypeScript will show a type error because it cannot guarantee the method exists on all types in the union.
How can you safely use a union type variable that could be a string or a number?
AUse a type check like typeof
BCall string methods directly
CAssign it to any type
DIgnore the type system
✗ Incorrect
Using typeof lets you check the type and safely use methods specific to that type.
Which of these is a valid union type declaration?
Alet x: string | number;
Blet x: string & number;
Clet x: string, number;
Dlet x: string-number;
✗ Incorrect
The correct syntax for union types uses the pipe | symbol.
Can union types include custom types like interfaces?
AUnion types are only for arrays
BNo, only primitive types are allowed
COnly classes can be used in union types
DYes, union types can combine any types including interfaces
✗ Incorrect
Union types can combine any types, including interfaces, classes, and primitives.
Describe how to declare and use a union type in TypeScript with an example.
Think about how a variable can hold a string or a number.
You got /3 concepts.
Explain how TypeScript helps you safely work with union types using type narrowing.
Consider how you check if a variable is a string before calling string methods.
You got /3 concepts.
Practice
(1/5)
1. What does a union type in TypeScript allow a variable to do?
easy
A. Hold values of multiple specified types safely
B. Hold only one fixed type value
C. Automatically convert types at runtime
D. Restrict values to a single primitive type
Solution
Step 1: Understand union type purpose
A union type lets a variable accept values from multiple specified types, not just one.
Step 2: Compare options with definition
Only Hold values of multiple specified types safely correctly describes this behavior; others describe fixed or automatic conversions which union types do not do.
Final Answer:
Hold values of multiple specified types safely -> Option A
Quick Check:
Union type = multiple types allowed [OK]
Hint: Union types use | to allow multiple types [OK]
Common Mistakes:
Thinking union types convert values automatically
Believing union types restrict to one type only
Confusing union with intersection types
2. Which of the following is the correct syntax to declare a variable value that can be either a string or a number?
easy
A. let value: string | number;
B. let value: string & number;
C. let value: string, number;
D. let value: string | number[];
Solution
Step 1: Recall union type syntax
Union types use the pipe symbol | between types without parentheses needed.
Step 2: Evaluate each option
let value: string | number; uses correct syntax: string | number. let value: string & number; uses & which means intersection, not union. let value: string, number; uses comma which is invalid. let value: string | number[]; uses number[] which is an array of numbers, not a single number.
Final Answer:
let value: string | number; -> Option A
Quick Check:
Union syntax uses | without commas [OK]
Hint: Use | between types, no commas or & for union [OK]
Common Mistakes:
Using & instead of | for union types
Separating types with commas
Using number[] instead of number
3. What will be the output of this TypeScript code?
function printId(id: string | number) {
if (typeof id === 'string') {
console.log('ID is a string: ' + id.toUpperCase());
} else {
console.log('ID is a number: ' + id.toFixed(2));
}
}
printId(42);
medium
A. ID is a string: 42
B. ID is a number: 42
C. ID is a number: 42.00
D. Runtime error due to wrong method
Solution
Step 1: Analyze type check and method calls
The function checks if id is a string or number. For number, it calls toFixed(2) which formats number with 2 decimals.
Step 2: Apply input and output
Input is 42 (number), so else branch runs and prints 'ID is a number: 42.00'.
Final Answer:
ID is a number: 42.00 -> Option C
Quick Check:
Number uses toFixed(2) = 42.00 [OK]
Hint: Check typeof before calling type-specific methods [OK]
Common Mistakes:
Calling string methods on numbers without check
Expecting no decimal places in toFixed output
Ignoring type narrowing with typeof
4. Identify the error in this TypeScript code using union types:
function formatInput(input: string | number) {
return input.toUpperCase();
}
medium
A. No error, code works fine
B. Error: toUpperCase() not available on number
C. Error: Missing return type annotation
D. Error: Union types cannot be used in functions
Solution
Step 1: Check method usage on union type
Method toUpperCase() exists on string but not on number.
Step 2: Understand type safety with union
Without checking type, calling toUpperCase() on input causes error because input might be number.
Final Answer:
Error: toUpperCase() not available on number -> Option B
Quick Check:
Call methods only after type check [OK]
Hint: Always check type before calling type-specific methods [OK]
Common Mistakes:
Calling string methods on union without type check
Assuming union types allow all methods
Ignoring compiler errors about method availability
5. Given this TypeScript code, what will be the output?
type Result = string | null;
function process(value: Result) {
return value?.toUpperCase() ?? 'No value';
}
console.log(process(null));
console.log(process('hello'));
hard
A. No value\nhello
B. null\nhello
C. Error: Cannot call toUpperCase on null
D. No value\nHELLO
Solution
Step 1: Understand optional chaining and nullish coalescing
The expression value?.toUpperCase() calls toUpperCase() only if value is not null or undefined. Otherwise, it returns undefined.
Step 2: Apply nullish coalescing fallback
If the left side is undefined, ?? 'No value' returns 'No value'. So for null, output is 'No value'. For 'hello', it returns 'HELLO'.
Final Answer:
No value
HELLO -> Option D
Quick Check:
Optional chaining + ?? handles null safely [OK]
Hint: Use ?. and ?? to safely handle null in unions [OK]
Common Mistakes:
Expecting error when calling method on null
Ignoring optional chaining usage
Confusing null and undefined handling
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.