0
0
Typescriptprogramming~10 mins

Why generics are needed 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 create a generic function that returns the input value.

Typescript
function identity<T>(value: T): T {
  return value;
}
Drag options to blanks, or click blank then click option'
Aitem
Binput
Cvalue
Darg
Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name that does not match the return statement.
2fill in blank
medium

Complete the code to declare a generic array of type T.

Typescript
let items: Array<[1]> = [];
Drag options to blanks, or click blank then click option'
AT
Bany
Cnumber
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific type like number or string instead of the generic type.
3fill in blank
hard

Fix the error in the generic function parameter type.

Typescript
function wrapInArray<T>(value: [1]): T[] {
  return [value];
}
Drag options to blanks, or click blank then click option'
AArray
BT
Cany
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-generic type like Array or object for the parameter.
4fill in blank
hard

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

Typescript
function firstElement<[1]>(arr: [2][]): [1] {
  return arr[0];
}
Drag options to blanks, or click blank then click option'
AT
BU
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names for the parameter and return type.
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.

Typescript
function mapArray<[1], [2]>(arr: [1][], func: (item: [1]) => [2]): [2][] {
  return arr.map(func);
}
Drag options to blanks, or click blank then click option'
AT
BU
CV
DW
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the generic type parameters or using inconsistent names.