Bird
Raised Fist0
Typescriptprogramming~20 mins

Why type design patterns matter in Typescript - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Type Design Mastery
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 a union type?
Consider this TypeScript code that uses a union type to accept different shapes of input. What will be logged to the console?
Typescript
type Shape = { kind: 'circle'; radius: number } | { kind: 'square'; side: number };

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

console.log(area({ kind: 'circle', radius: 3 }));
ATypeError at runtime
B9
C28.274333882308138
Dundefined
Attempts:
2 left
💡 Hint
Think about the formula for the area of a circle and how the union type helps the function know which property to use.
🧠 Conceptual
intermediate
1:30remaining
Why use type guards in TypeScript?
Which of the following best explains why type guards are important in TypeScript type design patterns?
AThey allow the compiler to narrow down types so you can safely access properties specific to a type.
BThey automatically convert types at runtime to avoid errors.
CThey replace the need for interfaces in complex applications.
DThey prevent any type errors by disabling type checking.
Attempts:
2 left
💡 Hint
Think about how TypeScript knows which properties exist on a variable when it has multiple possible types.
🔧 Debug
advanced
2:00remaining
What error does this TypeScript code produce?
Look at this TypeScript code snippet using intersection types. What error will the compiler show?
Typescript
type A = { x: number };
type B = { y: string };
type C = A & B;

const obj: C = { x: 10, y: 20 };
ANo error, code compiles fine.
BType 'number' is not assignable to type 'string' for property 'y'.
CProperty 'x' is missing in type '{ x: 10, y: 20 }'.
DType 'string' is not assignable to type 'number' for property 'x'.
Attempts:
2 left
💡 Hint
Check the type of property 'y' in the object and in the type definition.
🚀 Application
advanced
2:30remaining
How to design a discriminated union for API responses?
You want to design a TypeScript type for API responses that can be either success or error. Which design pattern below correctly models this with discriminated unions?
Atype ApiResponse = { success: boolean; message: string };
Btype ApiResponse = { data: string } & { error: string };
Ctype ApiResponse = { status: string; data?: string; error?: string };
Dtype ApiResponse = { status: 'success'; data: string } | { status: 'error'; error: string };
Attempts:
2 left
💡 Hint
Discriminated unions use a common property with literal types to distinguish variants.
❓ Predict Output
expert
3:00remaining
What is the output of this TypeScript code using conditional types?
Given this TypeScript code with conditional types, what will be the output when running the code?
Typescript
type IsString<T> = T extends string ? 'yes' : 'no';

function checkType<T>(value: T): IsString<T> {
  return (typeof value === 'string' ? 'yes' : 'no') as IsString<T>;
}

console.log(checkType(123));
console.log(checkType('hello'));
Ano\nyes
Byes\nno
CTypeError at runtime
Dundefined\nundefined
Attempts:
2 left
💡 Hint
Look at how the conditional type IsString works and how the function returns values based on typeof.

Practice

(1/5)
1. Why are type design patterns important in TypeScript?
interface User { name: string; age: number; }
easy
A. They help organize data shapes clearly and catch errors early.
B. They make the code run faster at runtime.
C. They allow you to write code without any rules.
D. They automatically fix bugs in your code.

Solution

  1. Step 1: Understand the role of type design patterns

    Type design patterns define how data is structured, making it clear what shape data should have.
  2. Step 2: Recognize benefits in TypeScript

    They help catch mistakes early by checking types before running the code, improving code quality and readability.
  3. Final Answer:

    They help organize data shapes clearly and catch errors early. -> Option A
  4. Quick Check:

    Type design patterns = Organize + Catch errors [OK]
Hint: Think: patterns = clear data + early error catch [OK]
Common Mistakes:
  • Confusing type patterns with runtime speed
  • Believing types fix bugs automatically
  • Ignoring the role of type safety
2. Which of the following is the correct syntax to define a type alias for a user object with a name and age in TypeScript?
easy
A. type User = name: string, age: number;
B. type User = (name: string, age: number);
C. type User = { name: string; age: number; };
D. type User = [name: string, age: number];

Solution

  1. Step 1: Recall type alias syntax

    Type aliases use the syntax: type Name = { ... } to define object shapes.
  2. Step 2: Check each option

    type User = { name: string; age: number; }; correctly uses curly braces and property types. Others use invalid syntax for object types.
  3. Final Answer:

    type User = { name: string; age: number; }; -> Option C
  4. Quick Check:

    Type alias object = curly braces [OK]
Hint: Use curly braces for object types in type aliases [OK]
Common Mistakes:
  • Using parentheses instead of braces
  • Missing braces around properties
  • Using array syntax for objects
3. What will be the output of this TypeScript code?
type Point = { x: number; y: number };
const p: Point = { x: 5, y: 10 };
console.log(p.x + p.y);
medium
A. 510
B. Error: Type mismatch
C. NaN
D. 15

Solution

  1. Step 1: Understand the Point type and object

    The object p has properties x = 5 and y = 10, both numbers.
  2. Step 2: Calculate the sum of p.x and p.y

    Adding 5 + 10 results in 15, which is logged to the console.
  3. Final Answer:

    15 -> Option D
  4. Quick Check:

    5 + 10 = 15 [OK]
Hint: Add numeric properties directly for sum [OK]
Common Mistakes:
  • Concatenating numbers as strings
  • Expecting a type error at runtime
  • Confusing object with array
4. Identify the error in this TypeScript code and fix it:
type Product = { id: number; name: string };
const product: Product = { id: 1, name: 100 };
medium
A. Change name to a string value, e.g., 'Book'.
B. Change id to a string value, e.g., '1'.
C. Remove the type annotation from product.
D. Add a new property price: number.

Solution

  1. Step 1: Check the type of each property

    The name property expects a string, but 100 is a number, causing a type error.
  2. Step 2: Fix the type mismatch

    Assign a string value to name, for example, 'Book', to match the type definition.
  3. Final Answer:

    Change name to a string value, e.g., 'Book'. -> Option A
  4. Quick Check:

    Property types must match definition [OK]
Hint: Match property types exactly as defined [OK]
Common Mistakes:
  • Assigning wrong types to properties
  • Removing type annotations unnecessarily
  • Adding unrelated properties without fixing errors
5. You want to design a type pattern for a list of users where each user has a name and an optional email. Which type design pattern is best to ensure clarity and maintainability?
hard
A. Use a union type: type User = { name: string } | { email: string }
B. Use an interface with optional email property: interface User { name: string; email?: string; }
C. Use a type alias with email as a required string: type User = { name: string; email: string; }
D. Use any type: type User = any;

Solution

  1. Step 1: Understand the requirement for optional email

    The email property should be optional, meaning it may or may not exist on a user object.
  2. Step 2: Choose the pattern that supports optional properties clearly

    Using an interface with email?: string marks email as optional and keeps the type clear and maintainable.
  3. Final Answer:

    Use an interface with optional email property: interface User { name: string; email?: string; } -> Option B
  4. Quick Check:

    Optional property syntax = ? [OK]
Hint: Use ? to mark optional properties in interfaces [OK]
Common Mistakes:
  • Making optional properties required
  • Using union types incorrectly for optional fields
  • Using any type which loses 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