0
0
Typescriptprogramming~10 mins

Type-safe builder pattern in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a builder class.

Typescript
class UserBuilder {
  private name: string = '';
  private age: number = 0;

  setName(name: string): this {
    this.name = name;
    return this;
  }
}
Drag options to blanks, or click blank then click option'
Aself
Bthis()
Cself()
Dthis
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a wrong keyword like 'self' which is not valid in TypeScript.
Calling 'this()' as if it were a function.
2fill in blank
medium

Complete the code to add a build method that returns the constructed object.

Typescript
class UserBuilder {
  private name: string = '';
  private age: number = 0;

  build(): [1] {
    return { name: this.name, age: this.age };
  }
}
Drag options to blanks, or click blank then click option'
A{ name: string; age: number }
Bany
Cobject
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using a class name that is not defined.
Using 'any' which loses type safety.
3fill in blank
hard

Fix the error in the builder method to ensure type safety for setting age.

Typescript
setAge(age: [1]): this {
  if (age < 0) throw new Error('Age cannot be negative');
  this.age = age;
  return this;
}
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' which causes comparison errors.
Using 'any' which removes type safety.
4fill in blank
hard

Fill both blanks to create a type-safe builder that requires name and age before building.

Typescript
type User = { name: string; age: number };

class UserBuilder [1] {
  private user: Partial<User> = {};

  setName(name: string): [2] {
    this.user.name = name;
    return this;
  }
}
Drag options to blanks, or click blank then click option'
A<T extends Partial<User> = {}>
B<T extends User>
Cimplements User
Dextends User
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'implements' or 'extends' incorrectly for this pattern.
Not using generics to track property setting.
5fill in blank
hard

Fill all three blanks to complete the build method that only allows building when all properties are set.

Typescript
build(this: UserBuilder[1]): User {
  if (!this.user.name || !this.user.age) {
    throw new Error('Missing properties');
  }
  return this.user as User;
}
Drag options to blanks, or click blank then click option'
A<T extends {}>
B<T extends Partial<User>>
C<T extends User>
D<T>
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic constraint that allows partial properties.
Not constraining the generic type at all.