0
0
Typescriptprogramming~20 mins

Type alias for unions in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Union Type Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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"));
A"Operation succeeded"
BCompilation error
CTypeError at runtime
D"Operation failed"
Attempts:
2 left
💡 Hint
Check what the function returns when the input is "success".
Predict Output
intermediate
2: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;
A"number"
B"string"
C"undefined"
D"object"
Attempts:
2 left
💡 Hint
Look at the last assignment to userId and what typeof returns.
🔧 Debug
advanced
2: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" });
AType 'string' is not assignable to type 'number'.
BNo error, prints undefined
CProperty 'code' does not exist on type '{ message: string; }'.
DFunction handleResponse is missing return type
Attempts:
2 left
💡 Hint
Check if all union members have the property 'code'.
📝 Syntax
advanced
2:00remaining
Correct syntax for union type alias
Which option correctly defines a type alias 'Shape' that can be either 'circle' or 'square'?
Atype Shape = "circle" | "square";
Btype Shape = "circle", "square";
Ctype Shape = "circle" & "square";
Dtype Shape = ("circle" | "square")[];
Attempts:
2 left
💡 Hint
Union types use the pipe symbol | between types.
🚀 Application
expert
2: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;
A1
B3
C9
D6
Attempts:
2 left
💡 Hint
Count all unique literals in the union.