Complete the code to declare a generic function with a constraint that the type must extend an object.
function identity<T [1] object>(arg: T): T { return arg; }
The keyword extends is used in TypeScript to constrain a generic type parameter to types that satisfy the given constraint, such as object.
Complete the code to constrain the generic type to have a 'length' property.
function logLength<T [1] { length: number }>(arg: T): T { console.log(arg.length); return arg; }
The extends keyword is used to constrain the generic type T to types that have a length property of type number.
Fix the error in the generic function declaration by completing the constraint.
function getProperty<T, K [1] keyof T>(obj: T, key: K) { return obj[key]; }
The generic type K must be constrained to keys of T using extends keyof T.
Fill both blanks to create a generic function that accepts an array of items extending a base interface.
interface Base {
id: number;
}
function processItems<T [1] Base>(items: T[2]) {
items.forEach(item => console.log(item.id));
}The generic type T extends Base, and the parameter items is an array of T using [] syntax.
Fill all three blanks to define a generic class with a constraint and a method using the generic type.
class Container<T [1] { name: string }> { private value: T; constructor(value: T) { this.value = value; } getName(): [2] { return this.value[3]; } }
value instead of value.name.The generic type T extends an object with a name property. The method getName returns the name property of value.