Bird
Raised Fist0
Typescriptprogramming~20 mins

Union type syntax and behavior in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 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
What is the output of this union type check?
Consider the following TypeScript code. What will be logged to the console?
Typescript
type Result = string | number;

function printResult(value: Result) {
  if (typeof value === 'string') {
    console.log(value.toUpperCase());
  } else {
    console.log(value + 10);
  }
}

printResult('hello');
printResult(5);
AHELLO and 5
B"hello" and 15
CTypeError at runtime
D"HELLO" and 15
Attempts:
2 left
💡 Hint
Check how the typeof operator distinguishes between string and number.
🧠 Conceptual
intermediate
1:30remaining
Which union type allows both string and boolean values?
Which of the following TypeScript union types correctly allows a variable to hold either a string or a boolean?
Atype MyType = string | boolean;
Btype MyType = string & boolean;
Ctype MyType = string, boolean;
Dtype MyType = string || boolean;
Attempts:
2 left
💡 Hint
Union types use the pipe symbol | to combine types.
🔧 Debug
advanced
2:00remaining
Why does this union type assignment cause an error?
Examine the code below. Why does the assignment cause a TypeScript error?
Typescript
type ID = number | string;

let userId: ID = true;
ABecause union types cannot include boolean values.
BBecause 'true' is assignable to 'number | string' but needs explicit casting.
CBecause 'true' is not assignable to type 'number | string'.
DBecause 'userId' must be declared with 'const' instead of 'let'.
Attempts:
2 left
💡 Hint
Check the allowed types in the union and the assigned value type.
❓ Predict Output
advanced
2:30remaining
What is the output of this function with union types and type narrowing?
What will the following TypeScript code output when executed?
Typescript
type Input = string | number | boolean;

function describe(input: Input) {
  switch (typeof input) {
    case 'string':
      return `String: ${input.length}`;
    case 'number':
      return `Number: ${input * 2}`;
    case 'boolean':
      return `Boolean: ${input ? 'yes' : 'no'}`;
  }
}

console.log(describe('abc'));
console.log(describe(4));
console.log(describe(false));
A"String: abc", "Number: 4", "Boolean: false"
B"String: 3", "Number: 8", "Boolean: no"
C"String: 3", "Number: 4", "Boolean: no"
DRuntime error due to missing default case
Attempts:
2 left
💡 Hint
Look at how typeof narrows the type and what each case returns.
🧠 Conceptual
expert
3:00remaining
How does TypeScript handle union types with overlapping properties?
Given these interfaces and union type, what is the type of 'value.name' inside the function?
Typescript
interface A { name: string; age: number; }
interface B { name: string; location: string; }

type AB = A | B;

function printName(value: AB) {
  return value.name;
}
Astring
Bstring | undefined
Cnever
DTypeScript error: Property 'name' does not exist on type 'AB'
Attempts:
2 left
💡 Hint
Check which properties are common to both interfaces in the union.

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

  1. Step 1: Understand union type purpose

    A union type lets a variable accept values from multiple specified types, not just one.
  2. 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.
  3. Final Answer:

    Hold values of multiple specified types safely -> Option A
  4. 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

  1. Step 1: Recall union type syntax

    Union types use the pipe symbol | between types without parentheses needed.
  2. 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.
  3. Final Answer:

    let value: string | number; -> Option A
  4. 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

  1. 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.
  2. Step 2: Apply input and output

    Input is 42 (number), so else branch runs and prints 'ID is a number: 42.00'.
  3. Final Answer:

    ID is a number: 42.00 -> Option C
  4. 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

  1. Step 1: Check method usage on union type

    Method toUpperCase() exists on string but not on number.
  2. Step 2: Understand type safety with union

    Without checking type, calling toUpperCase() on input causes error because input might be number.
  3. Final Answer:

    Error: toUpperCase() not available on number -> Option B
  4. 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

  1. 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.
  2. 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'.
  3. Final Answer:

    No value HELLO -> Option D
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard