Bird
Raised Fist0
Typescriptprogramming~20 mins

Type-safe builder pattern in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Type-safe Builder Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple type-safe builder
What is the output of this TypeScript code using a type-safe builder pattern?
Typescript
class CarBuilder {
  private color?: string;
  private wheels?: number;

  setColor(color: string) {
    this.color = color;
    return this;
  }

  setWheels(wheels: number) {
    this.wheels = wheels;
    return this;
  }

  build(): { color: string; wheels: number } {
    if (!this.color || !this.wheels) {
      throw new Error('Missing properties');
    }
    return { color: this.color, wheels: this.wheels };
  }
}

const car = new CarBuilder().setColor('red').setWheels(4).build();
console.log(car);
AError: Missing properties
B{ color: 'red', wheels: 4 }
C{ color: undefined, wheels: 4 }
D{ color: 'red', wheels: undefined }
Attempts:
2 left
💡 Hint
Check if all required properties are set before building.
🧠 Conceptual
intermediate
1:30remaining
Purpose of type-safe builder pattern
What is the main advantage of using a type-safe builder pattern in TypeScript?
AIt allows creating objects without specifying any properties.
BIt automatically generates UI forms for object creation.
CIt makes the code run faster by skipping type checks.
DIt ensures all required properties are set before object creation, preventing runtime errors.
Attempts:
2 left
💡 Hint
Think about how type safety helps prevent mistakes.
🔧 Debug
advanced
2:30remaining
Identify the error in this builder pattern
What error will this TypeScript code produce when calling build()?
Typescript
class UserBuilder {
  private name?: string;
  private age?: number;

  setName(name: string) {
    this.name = name;
    return this;
  }

  setAge(age: number) {
    this.age = age;
    return this;
  }

  build(): { name: string; age: number } {
    if (!this.name && !this.age) {
      throw new Error('Missing properties');
    }
    return { name: this.name!, age: this.age! };
  }
}

const user = new UserBuilder().setName('Alice').build();
console.log(user);
A{ name: 'Alice', age: undefined }
BTypeError at runtime
C{ name: 'Alice', age: number }
DError: Missing properties
Attempts:
2 left
💡 Hint
Check the condition in the if statement inside build().
📝 Syntax
advanced
2:30remaining
Which option correctly enforces required properties in builder?
Which TypeScript code snippet correctly enforces that 'title' and 'author' must be set before calling build() in a type-safe builder?
A
class BookBuilder {
  private title?: string;
  private author?: string;

  setTitle(title: string) {
    this.title = title;
    return this;
  }

  setAuthor(author: string) {
    this.author = author;
    return this;
  }

  build(): { title: string; author: string } {
    if (!this.title || !this.author) {
      throw new Error('Missing properties');
    }
    return { title: this.title, author: this.author };
  }
}
B
class BookBuilder {
  private title: string;
  private author: string;

  setTitle(title: string) {
    this.title = title;
    return this;
  }

  setAuthor(author: string) {
    this.author = author;
    return this;
  }

  build(): { title: string; author: string } {
    return { title: this.title, author: this.author };
  }
}
C
class BookBuilder {
  private title?: string;
  private author?: string;

  setTitle(title: string) {
    this.title = title;
    return this;
  }

  setAuthor(author: string) {
    this.author = author;
    return this;
  }

  build(): { title: string; author: string } {
    return { title: this.title!, author: this.author! };
  }
}
D
class BookBuilder {
  private title?: string;
  private author?: string;

  setTitle(title: string) {
    this.title = title;
    return this;
  }

  setAuthor(author: string) {
    this.author = author;
    return this;
  }

  build(): { title: string; author: string } {
    if (this.title === undefined || this.author === undefined) {
      throw new Error('Missing properties');
    }
    return { title: this.title!, author: this.author! };
  }
}
Attempts:
2 left
💡 Hint
Check the condition that throws an error if any required property is missing.
🚀 Application
expert
3:00remaining
How many valid objects can this type-safe builder create?
Given this TypeScript type-safe builder that requires setting 'x' and 'y' as numbers and optionally 'label' as string, how many distinct valid objects can be created?
Typescript
class PointBuilder {
  private x?: number;
  private y?: number;
  private label?: string;

  setX(x: number) {
    this.x = x;
    return this;
  }

  setY(y: number) {
    this.y = y;
    return this;
  }

  setLabel(label: string) {
    this.label = label;
    return this;
  }

  build(): { x: number; y: number; label?: string } {
    if (this.x === undefined || this.y === undefined) {
      throw new Error('Missing required properties');
    }
    return this.label === undefined ? { x: this.x, y: this.y } : { x: this.x, y: this.y, label: this.label };
  }
}

const builder = new PointBuilder();
AExactly 2, one with label and one without.
BOnly 1, because label is optional and x,y must be fixed.
CInfinite, because x and y can be any number and label is optional.
DZero, because the builder does not set any default values.
Attempts:
2 left
💡 Hint
Consider the range of possible values for x and y.

Practice

(1/5)
1.

What is the main benefit of using a type-safe builder pattern in TypeScript?

easy
A. It ensures all required properties are set before creating the object.
B. It makes the code run faster at runtime.
C. It automatically generates UI forms.
D. It removes the need for interfaces.

Solution

  1. Step 1: Understand the purpose of type-safe builder pattern

    The pattern helps build objects step-by-step while ensuring correctness.
  2. Step 2: Identify the key benefit

    It uses TypeScript's type system to check that all required properties are set before final object creation.
  3. Final Answer:

    It ensures all required properties are set before creating the object. -> Option A
  4. Quick Check:

    Type safety = required properties checked [OK]
Hint: Remember: type-safe means catching errors before running [OK]
Common Mistakes:
  • Thinking it improves runtime speed
  • Confusing it with UI generation
  • Assuming it removes interfaces
2.

Which of the following is the correct way to declare a generic builder class in TypeScript?

class Builder<T> {
private data: T;
constructor() {
this.data = {} as T;
}
build(): T {
return this.data;
}
}
easy
A. class Builder<T> { private data: T; constructor() { this.data = undefined; } build(): T { return this.data; } }
B. class Builder { private data: any; constructor() { this.data = {}; } build(): any { return this.data; } }
C. class Builder<T> { private data: T; constructor() { this.data = {} as T; } build(): T { return this.data; } }
D. class Builder<T> { private data: T; constructor() { this.data = null; } build(): T { return this.data; } }

Solution

  1. Step 1: Check generic class declaration

    class Builder<T> { private data: T; constructor() { this.data = {} as T; } build(): T { return this.data; } } correctly declares a generic class with <T> and initializes data as {} as T.
  2. Step 2: Verify build method return type

    The build() method returns data typed as T, matching the generic type.
  3. Final Answer:

    class Builder<T> { private data: T; constructor() { this.data = {} as T; } build(): T { return this.data; } } -> Option C
  4. Quick Check:

    Generic class with typed data = class Builder<T> { private data: T; constructor() { this.data = {} as T; } build(): T { return this.data; } } [OK]
Hint: Look for generic <T> and proper initialization [OK]
Common Mistakes:
  • Using any instead of generic type
  • Initializing data with null or undefined
  • Missing generic parameter in class
3.

Consider this TypeScript code using a type-safe builder pattern:

interface User {
name: string;
age: number;
}

class UserBuilder {
private user = {} as Partial<User>;
setName(name: string) { this.user.name = name; return this; }
setAge(age: number) { this.user.age = age; return this; }
build(): User {
if (!this.user.name || !this.user.age) throw new Error('Missing fields');
return this.user as User;
}
}

const user = new UserBuilder().setName('Alice').setAge(30).build();
console.log(user);

What will be the output?

medium
A. { name: 'Alice', age: 30 }
B. Error: Missing fields
C. undefined
D. { name: 'Alice' }

Solution

  1. Step 1: Trace method calls on UserBuilder

    The builder sets name to 'Alice' and age to 30, so both required fields are set.
  2. Step 2: Check build method behavior

    Since both fields exist, no error is thrown, and the object is returned as User.
  3. Final Answer:

    { name: 'Alice', age: 30 } -> Option A
  4. Quick Check:

    All fields set = object returned [OK]
Hint: Check if all required fields are set before build [OK]
Common Mistakes:
  • Assuming error thrown even when fields set
  • Expecting undefined output
  • Missing age property in output
4.

Identify the error in this type-safe builder pattern code and select the fix:

interface Car {
make: string;
year: number;
}

class CarBuilder {
private car = {} as Partial<Car>;
setMake(make: string) { this.car.make = make; return this; }
setYear(year: number) { this.car.year = year; return this; }
build(): Car {
if (!this.car.make || !this.car.year) throw new Error('Missing fields');
return this.car;
}
}
medium
A. Initialize car as Car instead of Partial<Car>
B. Change return type of build() to Partial<Car>
C. Remove the if check for missing fields
D. Cast return value as Car: return this.car as Car;

Solution

  1. Step 1: Identify the type mismatch in build()

    The method returns this.car which is typed as Partial<Car>, but the return type is Car.
  2. Step 2: Fix by casting to Car

    To satisfy the return type, cast this.car as Car after checking required fields.
  3. Final Answer:

    Cast return value as Car: return this.car as Car; -> Option D
  4. Quick Check:

    Return type must match method signature [OK]
Hint: Cast partial object to full type after validation [OK]
Common Mistakes:
  • Changing return type to Partial<Car>
  • Removing validation checks
  • Initializing with full Car without setting fields
5.

You want to create a type-safe builder for a Product with required id and name, and optional description. Which approach best enforces setting required fields before build?

interface Product {
id: number;
name: string;
description?: string;
}

// Which builder pattern enforces required fields at compile time?
hard
A. Use a single class with optional properties and runtime checks in build()
B. Use generics with flags tracking set fields and conditional types for build()
C. Use a function that returns a partial Product object without checks
D. Use inheritance to extend a base builder class without generics

Solution

  1. Step 1: Understand compile-time enforcement

    Only generics with flags and conditional types can enforce required fields before build at compile time.
  2. Step 2: Compare options

    Use generics with flags tracking set fields and conditional types for build() uses TypeScript generics and conditional types to track which fields are set, preventing build() call until required fields are set.
  3. Final Answer:

    Use generics with flags tracking set fields and conditional types for build() -> Option B
  4. Quick Check:

    Compile-time safety = generics + conditional types [OK]
Hint: Use generics and conditional types to enforce required fields [OK]
Common Mistakes:
  • Relying only on runtime checks
  • Using inheritance without generics
  • Returning partial objects without enforcement
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