0
0
Typescriptprogramming~10 mins

Builder pattern with generics 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 generic Builder class.

Typescript
class Builder<[1]> {
  private value: T;
  constructor(initialValue: T) {
    this.value = initialValue;
  }
}
Drag options to blanks, or click blank then click option'
AK
BV
CT
DU
Attempts:
3 left
💡 Hint
Common Mistakes
Using a lowercase letter for the generic type parameter.
Not matching the generic parameter with the constructor argument.
2fill in blank
medium

Complete the method to set a new value in the Builder class.

Typescript
setValue(newValue: T): this {
  this.value = [1];
  return this;
}
Drag options to blanks, or click blank then click option'
AnewValue
Bvalue
Cthis.value
DnewVal
Attempts:
3 left
💡 Hint
Common Mistakes
Using an undefined variable like value instead of newValue.
Trying to assign this.value to itself.
3fill in blank
hard

Fix the error in the build method to return the stored value.

Typescript
build(): [1] {
  return this.value;
}
Drag options to blanks, or click blank then click option'
Avoid
BT
Cany
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using void which means no return value.
Using a concrete type like number which may not match T.
4fill in blank
hard

Fill both blanks to create a generic Builder method that updates a property and returns the builder.

Typescript
setProperty<K extends keyof T>(key: [1], value: T[K]): this {
  this.value[key] = [2];
  return this;
}
Drag options to blanks, or click blank then click option'
AK
Bkey
Cvalue
DT
Attempts:
3 left
💡 Hint
Common Mistakes
Using key as the type instead of the parameter name.
Assigning key instead of value to the property.
5fill in blank
hard

Fill all three blanks to create a generic Builder class with a static create method.

Typescript
class Builder<[1]> {
  private value: T;
  private constructor(initialValue: T) {
    this.value = initialValue;
  }

  static create<[2]>(initialValue: [3]): Builder<U> {
    return new Builder<U>(initialValue);
  }
}
Drag options to blanks, or click blank then click option'
AT
BU
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same generic parameter name for both class and static method.
Mismatching the generic parameter in the static method signature.