0
0
Typescriptprogramming~10 mins

Generic class with constraints 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 class with a constraint that T must have a 'length' property.

Typescript
class Container<[1]> {
  value: T;
  constructor(value: T) {
    this.value = value;
  }
  getLength(): number {
    return this.value.length;
  }
}
Drag options to blanks, or click blank then click option'
AT extends boolean
BT extends number
CT extends string
DT extends { length: number }
Attempts:
3 left
💡 Hint
Common Mistakes
Using a primitive type like number or boolean as a constraint which don't have length property.
Not using extends keyword to constrain the generic type.
2fill in blank
medium

Complete the code to create an instance of the generic class with a string, which satisfies the constraint.

Typescript
const stringContainer = new Container<[1]>("hello");
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Cboolean
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Using number or boolean which do not have length property.
Using object without specifying length property.
3fill in blank
hard

Fix the error in the generic class declaration by completing the constraint correctly.

Typescript
class DataHolder<[1]> {
  data: T;
  constructor(data: T) {
    this.data = data;
  }
  getSize(): number {
    return this.data.length;
  }
}
Drag options to blanks, or click blank then click option'
AT extends boolean
BT extends number
CT extends { length: number }
DT extends null
Attempts:
3 left
💡 Hint
Common Mistakes
Using primitive types like number or boolean which do not have length property.
Not using extends keyword.
4fill in blank
hard

Fill both blanks to define a generic class that accepts types with a 'length' property and a method that returns the length.

Typescript
class LengthChecker<[1]> {
  item: T;
  constructor(item: T) {
    this.item = item;
  }
  getLength(): [2] {
    return this.item.length;
  }
}
Drag options to blanks, or click blank then click option'
AT extends { length: number }
Bstring
Cnumber
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect return type for getLength.
Not constraining T to have length property.
5fill in blank
hard

Fill all three blanks to create a generic class with a constraint, a constructor, and a method that returns the length of the stored value.

Typescript
class GenericLength<[1]> {
  value: T;
  constructor([2]: T) {
    this.value = [3];
  }
  length(): number {
    return this.value.length;
  }
}
Drag options to blanks, or click blank then click option'
AT extends { length: number }
Bvalue
Ditem
Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name different from the assigned variable.
Not constraining the generic type.