Bird
Raised Fist0
Typescriptprogramming~20 mins

Why union types are needed in Typescript - Challenge Your Understanding

Choose your learning style10 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.

Practice

(1/5)
1. Why do we need union types in TypeScript?
let value: string | number;
easy
A. To make variables immutable
B. To allow a variable to hold more than one type of value
C. To force variables to be only one type
D. To automatically convert types at runtime

Solution

  1. Step 1: Understand union type declaration

    The syntax string | number means the variable can hold either a string or a number.
  2. Step 2: Identify the purpose of union types

    This flexibility allows one variable to store multiple types safely without errors.
  3. Final Answer:

    To allow a variable to hold more than one type of value -> Option B
  4. Quick Check:

    Union types = multiple allowed types [OK]
Hint: Union types let variables hold multiple types safely [OK]
Common Mistakes:
  • Thinking union types make variables immutable
  • Believing union types force a single type only
  • Confusing union types with automatic type conversion
2. Which of the following is the correct syntax to declare a variable that can be a string or number in TypeScript?
easy
A. let data: string & number;
B. let data: string or number;
C. let data: string | number;
D. let data: string, number;

Solution

  1. Step 1: Recall union type syntax

    Union types use the pipe symbol | to separate types.
  2. Step 2: Compare options

    let data: string | number; uses | correctly, while others use invalid syntax.
  3. Final Answer:

    let data: string | number; -> Option C
  4. Quick Check:

    Union syntax uses | symbol [OK]
Hint: Use | to separate types in union declarations [OK]
Common Mistakes:
  • Using & instead of | for union types
  • Separating types with commas
  • Writing 'or' instead of |
3. What will be the output of this TypeScript code?
function format(value: string | number) {
  if (typeof value === 'string') {
    return value.toUpperCase();
  } else {
    return value.toFixed(2);
  }
}

console.log(format('hello'));
console.log(format(3.14159));
medium
A. "HELLO" and 3
B. "hello" and "3.14159"
C. Error because value can be string or number
D. "HELLO" and "3.14"

Solution

  1. Step 1: Analyze function behavior for string input

    If input is a string, toUpperCase() converts it to uppercase, so 'hello' becomes 'HELLO'.
  2. Step 2: Analyze function behavior for number input

    If input is a number, toFixed(2) formats it to 2 decimal places, so 3.14159 becomes '3.14'.
  3. Final Answer:

    "HELLO" and "3.14" -> Option D
  4. Quick Check:

    String upper + number fixed decimals = output [OK]
Hint: Check type with typeof before calling type-specific methods [OK]
Common Mistakes:
  • Assuming no type check needed and causing errors
  • Expecting original number without formatting
  • Confusing toFixed output as number instead of string
4. Identify the error in this TypeScript code using union types:
function printLength(value: string | number) {
  console.log(value.length);
}
printLength('test');
printLength(123);
medium
A. Error because number type has no 'length' property
B. Error because string type has no 'length' property
C. No error, code runs fine
D. Error because union types cannot be used in functions

Solution

  1. Step 1: Understand property access on union types

    Accessing length on value is unsafe because numbers don't have a length property.
  2. Step 2: Identify the error cause

    TypeScript will raise an error to prevent runtime failure when value is a number.
  3. Final Answer:

    Error because number type has no 'length' property -> Option A
  4. Quick Check:

    Accessing length on number causes error [OK]
Hint: Check type before accessing properties on union types [OK]
Common Mistakes:
  • Ignoring type checks and expecting no error
  • Thinking string has no length property
  • Believing union types disallow functions
5. You want a function that accepts either a string or an Array<string> and returns the total number of characters. Which is the best way to use union types to achieve this?
hard
A. function countChars(input: string | string[]) { if (typeof input === 'string') { return input.length; } else { return input.join('').length; } }
B. function countChars(input: string & string[]) { return input.length; }
C. function countChars(input: string | string[]) { return input.length; }
D. function countChars(input: any) { return input.length; }

Solution

  1. Step 1: Understand input types and their length

    A string has a length property; an array of strings also has length, but we want total characters, so we join the array first.
  2. Step 2: Check union type handling

    function countChars(input: string | string[]) { if (typeof input === 'string') { return input.length; } else { return input.join('').length; } } uses a type check to handle string and array separately, joining array elements to count total characters correctly.
  3. Final Answer:

    function countChars(input: string | string[]) { if (typeof input === 'string') { return input.length; } else { return input.join('').length; } } -> Option A
  4. Quick Check:

    Use type check and join array for total chars [OK]
Hint: Use typeof and array methods to handle union types properly [OK]
Common Mistakes:
  • Using intersection (&) instead of union (|)
  • Not checking type before accessing properties
  • Using any type losing type safety
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard