0
0
Typescriptprogramming~10 mins

Why advanced generics matter in Typescript - Test Your Understanding

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 that returns the input value.

Typescript
function identity<T>([1]: T): T {
  return value;
}
Drag options to blanks, or click blank then click option'
Aitem
Bvalue
Cinput
Darg
Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name different from the one returned causes errors.
2fill in blank
medium

Complete the code to define a generic interface with a property of type T.

Typescript
interface Box<[1]> {
  contents: T;
}
Drag options to blanks, or click blank then click option'
AU
BK
CV
DT
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic parameter name that does not match the property type causes errors.
3fill in blank
hard

Fix the error in the generic function to constrain T to types with 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'
Ainherits
Bimplements
Cextends
Dconforms
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect keywords like 'implements' or 'inherits' causes syntax errors.
4fill in blank
hard

Fill both blanks to create a generic function that returns the first element of an array of type T.

Typescript
function firstElement<[1]>(arr: [2][]): [1] {
  return arr[0];
}
Drag options to blanks, or click blank then click option'
AT
BU
DV
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic letters causes type mismatch errors.
5fill in blank
hard

Fill all three blanks to create a generic function that maps an array of type T to an array of type U using a callback.

Typescript
function mapArray<[1], [2]>(arr: [1][], callback: (item: [1]) => [2]): [2][] {
  return arr.map(callback);
}
Drag options to blanks, or click blank then click option'
AT
BU
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up generic types causes type errors in the callback or return value.