Challenge - 5 Problems
Union Type Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of union type alias usage
What is the output of this TypeScript code when compiled and run with Node.js?
Typescript
type Status = "success" | "error"; function respond(status: Status): string { if (status === "success") { return "Operation succeeded"; } else { return "Operation failed"; } } console.log(respond("success"));
Attempts:
2 left
💡 Hint
Check what the function returns when the input is "success".
✗ Incorrect
The type alias Status allows only "success" or "error". The function returns "Operation succeeded" when status is "success".
❓ Predict Output
intermediate2:00remaining
Value of variable with union type alias
What is the value of variable 'result' after running this code?
Typescript
type ID = number | string; let userId: ID = 123; userId = "abc"; const result = typeof userId;
Attempts:
2 left
💡 Hint
Look at the last assignment to userId and what typeof returns.
✗ Incorrect
userId is assigned the string "abc" last, so typeof userId is "string".
🔧 Debug
advanced2:00remaining
Identify the error in union type alias usage
What error does this TypeScript code produce?
Typescript
type Response = { code: number } | { message: string };
function handleResponse(res: Response) {
console.log(res.code);
}
handleResponse({ message: "Error" });Attempts:
2 left
💡 Hint
Check if all union members have the property 'code'.
✗ Incorrect
The union type Response can be either {code: number} or {message: string}. The code tries to access res.code without checking which type it is, causing a TypeScript error.
📝 Syntax
advanced2:00remaining
Correct syntax for union type alias
Which option correctly defines a type alias 'Shape' that can be either 'circle' or 'square'?
Attempts:
2 left
💡 Hint
Union types use the pipe symbol | between types.
✗ Incorrect
Option A correctly uses the union operator | to define Shape as either "circle" or "square".
🚀 Application
expert2:00remaining
Determine the number of possible values for a union type alias
Given this type alias, how many distinct values can a variable of type 'Level' hold?
Typescript
type Level = "low" | "medium" | "high" | 1 | 2 | 3;
Attempts:
2 left
💡 Hint
Count all unique literals in the union.
✗ Incorrect
The union has 3 string literals and 3 number literals, total 6 distinct values.