Bird
Raised Fist0
Typescriptprogramming~20 mins

Why patterns matter for safety in Typescript - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Pattern Safety 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 TypeScript code using pattern matching?
Consider this TypeScript code using a match-case style pattern with a discriminated union. What will be printed to the console?
Typescript
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; size: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'square':
      return shape.size ** 2;
  }
}

console.log(area({ kind: 'circle', radius: 3 }).toFixed(2));
ASyntax error: Unexpected token
B"28.27"
C"9.00"
DRuntime error: Property 'radius' does not exist on type 'Shape'
Attempts:
2 left
💡 Hint
Think about how the switch statement uses the 'kind' property to select the correct case.
❓ Predict Output
intermediate
2:00remaining
What error does this unsafe pattern cause?
What error will this TypeScript code produce when run, considering the unsafe access pattern?
Typescript
type User = { name: string; age?: number };

function getAge(user: User) {
  return user.age!.toFixed(0);
}

console.log(getAge({ name: 'Alice' }));
ATypeError: Cannot read property 'toFixed' of undefined
Bundefined
CSyntaxError: Unexpected token '.'
DNo error, prints '0'
Attempts:
2 left
💡 Hint
Check what happens if 'age' is missing and you try to call a method on it.
🧠 Conceptual
advanced
2:00remaining
Why do patterns help prevent runtime errors in TypeScript?
Which statement best explains why using patterns like discriminated unions and exhaustive checks improves safety in TypeScript?
AThey allow the compiler to verify all possible cases are handled, preventing unexpected undefined values.
BThey remove the need for type annotations entirely.
CThey make the code run faster by optimizing loops automatically.
DThey allow any type to be assigned without errors.
Attempts:
2 left
💡 Hint
Think about how the compiler helps catch missing cases.
❓ Predict Output
advanced
2:00remaining
What is the output of this TypeScript code using pattern guards?
What will this code print to the console?
Typescript
type Response = { status: 'success'; data: string } | { status: 'error'; message: string };

function handleResponse(resp: Response) {
  if (resp.status === 'success') {
    return resp.data.toUpperCase();
  } else {
    return resp.message.toLowerCase();
  }
}

console.log(handleResponse({ status: 'error', message: 'NOT FOUND' }));
ARuntime error: Cannot read property 'toLowerCase' of undefined
B"NOT FOUND"
C"not found"
DSyntax error: Missing return statement
Attempts:
2 left
💡 Hint
Check which branch runs for status 'error' and what method is called.
🧠 Conceptual
expert
3:00remaining
How do patterns in TypeScript improve code safety in large applications?
Select the best explanation for how using patterns like discriminated unions, exhaustive checks, and type guards improves safety in large TypeScript codebases.
AThey replace the need for unit testing entirely.
BThey automatically generate UI components based on types.
CThey allow ignoring type errors during compilation for faster builds.
DThey enforce strict handling of all possible data shapes, reducing bugs and improving maintainability.
Attempts:
2 left
💡 Hint
Think about how patterns help manage complexity and prevent errors.

Practice

(1/5)
1. Why is it important to use patterns in TypeScript for safety?
easy
A. They allow skipping type checks
B. They make the code run faster
C. They reduce the file size of the program
D. They help catch errors before running the code

Solution

  1. Step 1: Understand the role of patterns in TypeScript

    Patterns guide how to write code that avoids common mistakes and bugs.
  2. Step 2: Identify the benefit of safety patterns

    They help detect errors early, before the program runs, improving reliability.
  3. Final Answer:

    They help catch errors before running the code -> Option D
  4. Quick Check:

    Patterns catch errors early = A [OK]
Hint: Patterns catch bugs early, before runtime [OK]
Common Mistakes:
  • Thinking patterns only improve speed
  • Believing patterns reduce file size
  • Assuming patterns skip type checks
2. Which of the following is the correct TypeScript syntax to safely check if a variable value is a string before using it?
easy
A. if (typeof value === 'string') { /* use value */ }
B. if (value.type === 'string') { /* use value */ }
C. if (value instanceof 'string') { /* use value */ }
D. if (value === string) { /* use value */ }

Solution

  1. Step 1: Recall correct type checking syntax in TypeScript

    Use typeof variable === 'string' to check if a variable is a string.
  2. Step 2: Evaluate each option

    Only if (typeof value === 'string') { /* use value */ } uses the correct typeof operator and string comparison.
  3. Final Answer:

    if (typeof value === 'string') { /* use value */ } -> Option A
  4. Quick Check:

    Use typeof for type checks = D [OK]
Hint: Use typeof to check primitive types safely [OK]
Common Mistakes:
  • Using .type property which doesn't exist
  • Using instanceof with string literal
  • Comparing variable directly to string keyword
3. What will be the output of this TypeScript code?
function safeDivide(a: number, b: number): number | null {
  if (b === 0) return null;
  return a / b;
}

console.log(safeDivide(10, 2));
console.log(safeDivide(10, 0));
medium
A. 5 and null
B. 5 and Infinity
C. 5 and 0
D. Error at runtime

Solution

  1. Step 1: Analyze the function safeDivide

    If divisor b is zero, function returns null, else returns division result.
  2. Step 2: Evaluate console.log outputs

    First call: 10 / 2 = 5; second call: divisor is 0, returns null.
  3. Final Answer:

    5 and null -> Option A
  4. Quick Check:

    Division by zero returns null = C [OK]
Hint: Check for zero divisor to avoid runtime errors [OK]
Common Mistakes:
  • Expecting division by zero to return 0
  • Assuming runtime error instead of null
  • Confusing null with Infinity
4. Identify the error in this TypeScript code that tries to safely access a property:
interface User {
  name: string;
  age?: number;
}

function getUserAge(user: User): number {
  return user.age;
}
medium
A. Incorrect interface declaration syntax
B. Missing check for optional property before returning
C. Function should return string instead of number
D. No error, code is correct

Solution

  1. Step 1: Understand optional property in interface

    Property age is optional, so it may be undefined.
  2. Step 2: Check function return type vs possible undefined

    Function returns number but user.age can be undefined, causing a type error.
  3. Final Answer:

    Missing check for optional property before returning -> Option B
  4. Quick Check:

    Optional properties need checks = A [OK]
Hint: Check optional properties before use to avoid errors [OK]
Common Mistakes:
  • Ignoring optional property may be undefined
  • Thinking interface syntax is wrong
  • Confusing return type with property type
5. You want to create a safe pattern to transform an array of mixed values into an object mapping only string keys to their lengths. Which TypeScript pattern ensures safety and correctness?
const items = ["apple", 42, "banana", null, "cherry"];

// Which pattern is safest to create { [key: string]: number } mapping?
hard
A. Map all items to their length without checks
B. Use a for loop without type checks
C. Use a filter to keep only strings, then map to lengths
D. Assign items directly to object keys

Solution

  1. Step 1: Identify the need to filter only strings

    Since array has mixed types, filter out non-string values to avoid errors.
  2. Step 2: Map filtered strings to their lengths safely

    After filtering, create object entries mapping strings to their length, ensuring type safety.
  3. Final Answer:

    Use a filter to keep only strings, then map to lengths -> Option C
  4. Quick Check:

    Filter then map for safe transformation = B [OK]
Hint: Filter first, then map to avoid unsafe types [OK]
Common Mistakes:
  • Mapping without filtering causes runtime errors
  • Using loops without type checks
  • Assigning mixed types directly to object keys
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