Bird
Raised Fist0
Typescriptprogramming~10 mins

Why union types are needed in Typescript - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why union types are needed
Start: Variable declaration
↓
Assign value of type A
↓
Use variable
↓
Assign value of type B
↓
Use variable
↓
Type error if no union
↓
Union type allows multiple types
↓
No type error, flexible usage
↓
End
This flow shows how union types let a variable hold values of different types without errors.
Execution Sample
Typescript
let value: number | string;
value = 42;
console.log(value);
value = "hello";
console.log(value);
This code shows a variable that can hold either a number or a string and prints both.
Execution Table
StepActionVariable 'value' TypeVariable 'value' ValueOutputType Error?
1Declare 'value' with type number | stringnumber | stringundefinedNo
2Assign 42 to 'value'number | string42No
3Print 'value'number | string4242No
4Assign "hello" to 'value'number | string"hello"No
5Print 'value'number | string"hello"helloNo
6If 'value' was only number, assign string causes errornumberN/AYes
💡 Execution stops after demonstrating that union types prevent type errors when assigning different types.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
valueundefined42"hello""hello"
Key Moments - 3 Insights
Why does assigning a string to a variable declared only as number cause an error?
Because the variable expects only numbers, assigning a string breaks the type rule, shown in execution_table step 6.
How does the union type prevent type errors when assigning different types?
Union type allows multiple types, so assigning number or string is valid, as seen in execution_table steps 2 and 4.
What happens if we try to use the variable with a type not included in the union?
TypeScript will show an error because the value is not allowed by the union, preventing unsafe usage.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the type of 'value' after step 2?
Astring
Bnumber | string
Cnumber
Dundefined
💡 Hint
Check the 'Variable 'value' Type' column at step 2 in execution_table.
At which step does assigning a string to 'value' happen without error?
AStep 4
BStep 2
CStep 6
DStep 3
💡 Hint
Look at the 'Action' and 'Type Error?' columns in execution_table.
If 'value' was declared only as number, what would happen at step 4?
ANo error, string assigned
BVariable becomes undefined
CType error occurs
DValue changes to number automatically
💡 Hint
Refer to execution_table step 6 where type error is shown for assigning string to number.
Concept Snapshot
Union types let a variable hold values of multiple types.
Syntax: let varName: typeA | typeB;
Prevents errors when assigning different types.
Useful for flexible, safe code.
Without union, assigning wrong type causes error.
Full Transcript
This lesson shows why union types are needed in TypeScript. We start by declaring a variable that can hold either a number or a string using a union type. Then we assign a number and print it, followed by assigning a string and printing it again. The execution table tracks each step, showing the variable's type and value, and confirms no type errors occur. We also see that if the variable was declared only as a number, assigning a string would cause a type error. Key moments clarify why union types prevent errors and allow flexible variable usage. The quiz tests understanding of variable types and error conditions. The snapshot summarizes union types as a way to safely allow multiple types for a variable.

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