Bird
Raised Fist0
Typescriptprogramming~20 mins

Builder pattern with generics in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Builder Pattern Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a generic builder pattern example
What is the output of this TypeScript code using a generic builder pattern?
Typescript
class Builder<T> {
  private obj: Partial<T> = {};

  set<K extends keyof T>(key: K, value: T[K]): this {
    this.obj[key] = value;
    return this;
  }

  build(): T {
    return this.obj as T;
  }
}

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

const person = new Builder<Person>()
  .set('name', 'Alice')
  .set('age', 30)
  .build();

console.log(person);
ASyntaxError
B{"name":"Alice"}
C{"name":"Alice","age":30}
DTypeError at runtime
Attempts:
2 left
💡 Hint
Look at how the generic Builder class stores and returns the object.
❓ Predict Output
intermediate
2:00remaining
What error occurs with missing required property?
Given this generic builder pattern code, what error occurs when a required property is missing?
Typescript
class Builder<T> {
  private obj: Partial<T> = {};

  set<K extends keyof T>(key: K, value: T[K]): this {
    this.obj[key] = value;
    return this;
  }

  build(): T {
    return this.obj as T;
  }
}

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

const car = new Builder<Car>()
  .set('make', 'Toyota')
  .build();

console.log(car.year.toString());
ACompile-time error in TypeScript
BSyntaxError: Missing property 'year'
CNo error, outputs 'undefined'
DTypeError: Cannot read property 'toString' of undefined
Attempts:
2 left
💡 Hint
Check what happens when you access a property that was never set.
🔧 Debug
advanced
2:00remaining
Identify the bug in this generic builder pattern
What is the bug in this TypeScript generic builder pattern code?
Typescript
class Builder<T> {
  private obj: T = {} as T;

  set<K extends keyof T>(key: K, value: T[K]): this {
    this.obj[key] = value;
    return this;
  }

  build(): T {
    return this.obj;
  }
}

interface Book {
  title: string;
  pages: number;
}

const book = new Builder<Book>()
  .set('title', 'My Book')
  .set('pages', 100)
  .build();

console.log(book);
ANo error, outputs { title: 'My Book', pages: 100 }
BTypeError: Cannot assign to 'key' because 'obj' is not initialized properly
CSyntaxError: Missing colon in class property
DRuntime error: obj is undefined
Attempts:
2 left
💡 Hint
Check how obj is initialized and if {} is assignable to T.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a generic builder method?
Which of these method signatures correctly defines a generic set method in a builder pattern class in TypeScript?
Aset<K extends keyof T>(key: K, value: T[K]): this
Bset(key: string, value: any): this
Cset<K>(key: K, value: T[K]): this
Dset(key: keyof T, value: any): T
Attempts:
2 left
💡 Hint
Look for correct generic constraints and return type.
🚀 Application
expert
2:00remaining
How many properties does the built object have?
Consider this generic builder pattern code. How many properties does the final object have?
Typescript
class Builder<T> {
  private obj: Partial<T> = {};

  set<K extends keyof T>(key: K, value: T[K]): this {
    this.obj[key] = value;
    return this;
  }

  build(): T {
    return this.obj as T;
  }
}

interface Config {
  host: string;
  port: number;
  secure: boolean;
}

const config = new Builder<Config>()
  .set('host', 'localhost')
  .set('port', 8080)
  .build();

console.log(Object.keys(config).length);
A2
B3
C0
DRuntime error
Attempts:
2 left
💡 Hint
Only properties set by set() exist in the object.

Practice

(1/5)
1.

What is the main advantage of using the builder pattern with generics in TypeScript?

easy
A. It automatically generates UI components from objects.
B. It makes the code run faster by skipping type checks.
C. It allows creating different object types step-by-step with type safety.
D. It replaces all functions with classes.

Solution

  1. Step 1: Understand builder pattern purpose

    The builder pattern helps create complex objects step-by-step, improving clarity and flexibility.
  2. Step 2: Role of generics in TypeScript

    Generics allow the builder to work with any object type while keeping type safety, ensuring keys and values match.
  3. Final Answer:

    It allows creating different object types step-by-step with type safety. -> Option C
  4. Quick Check:

    Builder + generics = flexible, safe object creation [OK]
Hint: Generics + builder = reusable and type-safe object creation [OK]
Common Mistakes:
  • Thinking builder auto-generates UI
  • Believing it skips type checks
  • Confusing builder with replacing functions
2.

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

class Builder<T> {
private obj: T;
constructor() {
this.obj = {} as T;
}
set(key: keyof T, value: T[keyof T]): this {
this.obj[key] = value;
return this;
}
build(): T {
return this.obj;
}
}
easy
A. class Builder<T> { private obj: T; constructor() { this.obj = {} as T; } }
B. class Builder<T> { private obj: T; constructor() { this.obj = new T(); } }
C. class Builder { private obj: T; constructor() { this.obj = {} as T; } }
D. class Builder<T> { private obj: any; constructor() { this.obj = {}; } }

Solution

  1. Step 1: Check generic class declaration

    class Builder<T> { private obj: T; constructor() { this.obj = {} as T; } } correctly declares a generic class with <T> and initializes obj as {} as T.
  2. Step 2: Identify incorrect initializations

    class Builder<T> { private obj: T; constructor() { this.obj = new T(); } } tries new T() which is invalid in TypeScript. class Builder { private obj: T; constructor() { this.obj = {} as T; } } misses generic <T>. class Builder<T> { private obj: any; constructor() { this.obj = {}; } } uses any losing type safety.
  3. Final Answer:

    class Builder<T> { private obj: T; constructor() { this.obj = {} as T; } } -> Option A
  4. Quick Check:

    Generic class with {} as T init = class Builder<T> { private obj: T; constructor() { this.obj = {} as T; } } [OK]
Hint: Use {} as T to initialize generic object safely [OK]
Common Mistakes:
  • Trying to instantiate generic type with new
  • Forgetting to declare generic parameter <T>
  • Using any instead of generic type
3.

What will be the output of this code?

class Builder<T> {
private obj: T;
constructor() { this.obj = {} as T; }
set(key: keyof T, value: T[keyof T]): this {
this.obj[key] = value;
return this;
}
build(): T { return this.obj; }
}

interface Person { name: string; age: number; }
const person = new Builder<Person>()
.set('name', 'Alice')
.set('age', 30)
.build();
console.log(person);
medium
A. { name: 'Alice', age: 30 }
B. { name: 'Alice' }
C. Error: Cannot assign to 'name' of type 'T'
D. {}

Solution

  1. Step 1: Understand builder usage

    The builder sets 'name' to 'Alice' and 'age' to 30 on an empty object typed as Person.
  2. Step 2: Check final build output

    The build() method returns the object with both properties set, so output is { name: 'Alice', age: 30 }.
  3. Final Answer:

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

    Builder sets keys correctly = { name: 'Alice', age: 30 } [OK]
Hint: Builder sets keys stepwise, final object has all properties [OK]
Common Mistakes:
  • Expecting partial object missing keys
  • Thinking assignment causes error
  • Assuming empty object returned
4.

Identify the error in this builder class and select the fix:

class Builder<T> {
private obj: T;
constructor() { this.obj = {}; }
set(key: keyof T, value: T[keyof T]): this {
this.obj[key] = value;
return this;
}
build(): T { return this.obj; }
}
medium
A. Use any type for obj instead of T.
B. Change set method to accept key: string.
C. Remove generic <T> from class declaration.
D. Initialize obj as {} as T in constructor.

Solution

  1. Step 1: Identify initialization error

    Assigning {} directly to obj: T causes a type error because {} is not guaranteed to be T.
  2. Step 2: Correct initialization with type assertion

    Using {} as T tells TypeScript to treat empty object as type T safely during construction.
  3. Final Answer:

    Initialize obj as {} as T in constructor. -> Option D
  4. Quick Check:

    Use {} as T to fix generic object init [OK]
Hint: Use type assertion {} as T to initialize generic objects [OK]
Common Mistakes:
  • Assigning {} directly without assertion
  • Changing key type to string loses type safety
  • Removing generics breaks flexibility
5.

You want to build a generic builder that only allows setting properties defined in the object type and prevents setting undefined keys. Which TypeScript feature helps enforce this at compile time?

hard
A. Using any type for keys to allow flexibility.
B. Using keyof T as the key type in the set method.
C. Using unknown type for values to accept any value.
D. Using Partial<T> for the object storage.

Solution

  1. Step 1: Understand key restriction need

    To prevent setting keys not in the object type, the key parameter must be limited to valid keys.
  2. Step 2: Use keyof T for key type

    keyof T represents all valid keys of type T, so using it restricts keys to only those defined in T.
  3. Final Answer:

    Using keyof T as the key type in the set method. -> Option B
  4. Quick Check:

    keyof T restricts keys to valid properties [OK]
Hint: Use keyof T to limit keys to object properties [OK]
Common Mistakes:
  • Using any loses key restriction
  • Using unknown does not restrict keys
  • Partial<T> affects values, not 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