Complete the code to declare a builder class.
class UserBuilder { private name: string = ''; private age: number = 0; setName(name: string): this { this.name = name; return this; } }
In TypeScript, this refers to the current instance, allowing method chaining.
Complete the code to add a build method that returns the constructed object.
class UserBuilder { private name: string = ''; private age: number = 0; build(): [1] { return { name: this.name, age: this.age }; } }
The build method returns an object with name and age properties, so the return type should reflect that shape.
Fix the error in the builder method to ensure type safety for setting age.
setAge(age: [1]): this { if (age < 0) throw new Error('Age cannot be negative'); this.age = age; return this; }
The age should be a number to allow numeric comparison and assignment.
Fill both blanks to create a type-safe builder that requires name and age before building.
type User = { name: string; age: number };
class UserBuilder [1] {
private user: Partial<User> = {};
setName(name: string): [2] {
this.user.name = name;
return this;
}
}Using a generic type parameter T extending Partial<User> allows tracking which properties are set.
Fill all three blanks to complete the build method that only allows building when all properties are set.
build(this: UserBuilder[1]): User { if (!this.user.name || !this.user.age) { throw new Error('Missing properties'); } return this.user as User; }
The build method requires the generic type T to extend User, ensuring all properties are set.