Complete the code to declare a generic class with a constraint that T must have a 'length' property.
class Container<[1]> { value: T; constructor(value: T) { this.value = value; } getLength(): number { return this.value.length; } }
The generic type T is constrained to types that have a length property of type number. This allows accessing this.value.length safely.
Complete the code to create an instance of the generic class with a string, which satisfies the constraint.
const stringContainer = new Container<[1]>("hello");
The generic type parameter is string because strings have a length property, satisfying the constraint.
Fix the error in the generic class declaration by completing the constraint correctly.
class DataHolder<[1]> { data: T; constructor(data: T) { this.data = data; } getSize(): number { return this.data.length; } }
The constraint T extends { length: number } ensures that data.length is valid.
Fill both blanks to define a generic class that accepts types with a 'length' property and a method that returns the length.
class LengthChecker<[1]> { item: T; constructor(item: T) { this.item = item; } getLength(): [2] { return this.item.length; } }
The generic type T is constrained to have a length property. The method getLength returns a number because length is a number.
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.
class GenericLength<[1]> { value: T; constructor([2]: T) { this.value = [3]; } length(): number { return this.value.length; } }
The generic type T is constrained to have a length property. The constructor takes a parameter named value and assigns it to the class property this.value.