0
0
Typescriptprogramming~20 mins

Why union types are needed in Typescript - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Union Types Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use union types in TypeScript?

Consider a function that accepts either a string or a number. Why are union types useful in this case?

AThey disable type checking for the function parameters.
BThey allow the function to accept multiple types safely without losing type checking.
CThey force the function to accept only one type, either string or number, but not both.
DThey automatically convert all inputs to a single type before processing.
Attempts:
2 left
💡 Hint

Think about how TypeScript helps you write safer code when a variable can be more than one type.

Predict Output
intermediate
2:00remaining
Output of function using union types

What is the output of this TypeScript code?

Typescript
function formatInput(input: string | number): string {
  if (typeof input === 'number') {
    return `Number: ${input.toFixed(2)}`;
  } else {
    return `String: ${input.toUpperCase()}`;
  }
}

console.log(formatInput(3.14159));
console.log(formatInput('hello'));
A
Number: 3.14
String: hello
B
Number: 3.14159
String: hello
C
Number: 3.14
String: HELLO
DTypeError at runtime
Attempts:
2 left
💡 Hint

Look at how the function treats numbers and strings differently.

🔧 Debug
advanced
2:00remaining
Identify the error with union types

What error does this TypeScript code produce?

Typescript
function process(value: string | number) {
  return value.toFixed(2);
}

process('test');
AError: Property 'toFixed' does not exist on type 'string'.
BRuntime error: toFixed is not a function.
CError: Cannot call function without type assertion.
DNo error, outputs 'test'.
Attempts:
2 left
💡 Hint

Think about which types have the method toFixed.

📝 Syntax
advanced
2:00remaining
Correct union type syntax

Which option shows the correct way to declare a variable that can be a string or null?

Alet data: string, null;
Blet data: string & null;
Clet data: string || null;
Dlet data: string | null;
Attempts:
2 left
💡 Hint

Union types use a specific symbol between types.

🚀 Application
expert
3:00remaining
Using union types in function parameters

Given this function, what will be the value of result after calling combine(5, ' apples')?

Typescript
function combine(a: number | string, b: number | string): string {
  if (typeof a === 'number' && typeof b === 'string') {
    return a + b;
  } else if (typeof a === 'string' && typeof b === 'number') {
    return a + b.toString();
  } else {
    return 'Invalid input';
  }
}

const result = combine(5, ' apples');
A"5 apples"
B"5"
C"Invalid input"
DTypeError at runtime
Attempts:
2 left
💡 Hint

Check the types of a and b and which condition matches.