0
0
Typescriptprogramming~10 mins

Generic functions with arrays 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 that returns the first element of an array.

Typescript
function firstElement<[1]>(arr: [1][]): [1] {
  return arr[0];
}
Drag options to blanks, or click blank then click option'
AT
BK
CV
DU
Attempts:
3 left
💡 Hint
Common Mistakes
Using a lowercase letter for the generic type parameter.
Using different type parameters for the array and return type.
2fill in blank
medium

Complete the code to create a generic function that returns the length of any array.

Typescript
function getLength<[1]>(items: [1][]): number {
  return items.length;
}
Drag options to blanks, or click blank then click option'
AU
BY
CX
DT
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic type parameter that does not match the array element type.
Forgetting to specify the generic type parameter in the function signature.
3fill in blank
hard

Fix the error in the generic function that swaps the first and last elements of an array.

Typescript
function swapFirstLast<[1]>(arr: [1][]): [1][] {
  const temp = arr[0];
  arr[0] = arr[arr.length - 1];
  arr[arr.length - 1] = temp;
  return arr;
}
Drag options to blanks, or click blank then click option'
AV
BU
CT
DW
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type parameters in the function signature and parameter.
Not declaring the generic type parameter at all.
4fill in blank
hard

Fill both blanks to create a generic function that filters an array based on a condition.

Typescript
function filterArray<[1]>(arr: [1][], predicate: (item: [2]) => boolean): [1][] {
  return arr.filter(predicate);
}
Drag options to blanks, or click blank then click option'
AT
BU
DV
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type parameters for the array and predicate argument.
Not using a generic type parameter at all.
5fill in blank
hard

Fill all three blanks to create a generic function that maps an array to another array using a transform function.

Typescript
function mapArray<[1] , [2]>(arr: [1][], transform: (item: [3]) => [2]): [2][] {
  return arr.map(transform);
}
Drag options to blanks, or click blank then click option'
AT
BU
DV
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same generic type parameter for input and output types.
Not declaring both generic type parameters.