0
0
Typescriptprogramming~10 mins

Generic constraints with extends 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 function with a constraint that the type must extend an object.

Typescript
function identity<T [1] object>(arg: T): T {
  return arg;
}
Drag options to blanks, or click blank then click option'
Aconforms
Bimplements
Cinherits
Dextends
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'implements' instead of 'extends' for generic constraints.
Using 'inherits' or 'conforms' which are not valid TypeScript keywords.
2fill in blank
medium

Complete the code to constrain the generic type to have a 'length' property.

Typescript
function logLength<T [1] { length: number }>(arg: T): T {
  console.log(arg.length);
  return arg;
}
Drag options to blanks, or click blank then click option'
Aextends
Bimplements
Cinherits
Dconforms
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'implements' instead of 'extends' for generic constraints.
Trying to use 'interface' keyword here.
3fill in blank
hard

Fix the error in the generic function declaration by completing the constraint.

Typescript
function getProperty<T, K [1] keyof T>(obj: T, key: K) {
  return obj[key];
}
Drag options to blanks, or click blank then click option'
Ainherits
Bimplements
Cextends
Dconforms
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'implements' instead of 'extends'.
Omitting the constraint entirely.
4fill in blank
hard

Fill both blanks to create a generic function that accepts an array of items extending a base interface.

Typescript
interface Base {
  id: number;
}

function processItems<T [1] Base>(items: T[2]) {
  items.forEach(item => console.log(item.id));
}
Drag options to blanks, or click blank then click option'
Aextends
Bimplements
C[]
DArray<T>
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'implements' instead of 'extends'.
Using 'Array' in the wrong blank.
5fill in blank
hard

Fill all three blanks to define a generic class with a constraint and a method using the generic type.

Typescript
class Container<T [1] { name: string }> {
  private value: T;
  constructor(value: T) {
    this.value = value;
  }
  getName(): [2] {
    return this.value[3];
  }
}
Drag options to blanks, or click blank then click option'
Aextends
BT
C.name
Dimplements
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'implements' instead of 'extends'.
Returning the whole value instead of value.name.
Incorrect return type.