0
0
Typescriptprogramming~10 mins

Generic function syntax 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 named identity.

Typescript
function identity[1](arg: T): T {
  return arg;
}
Drag options to blanks, or click blank then click option'
A<T>
B(T)
C[T]
D{T}
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or square brackets instead of angle brackets for generic parameters.
Forgetting to add the generic parameter after the function name.
2fill in blank
medium

Complete the code to call the generic function identity with a string argument.

Typescript
let output = identity[1]("hello");
Drag options to blanks, or click blank then click option'
A[string]
B(string)
C{string}
D<string>
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of angle brackets to specify the type argument.
Omitting the type argument when calling the generic function.
3fill in blank
hard

Fix the error in the generic function declaration by completing the missing generic parameter syntax.

Typescript
function getArray[1](items: T[]): T[] {
  return new Array().concat(items);
}
Drag options to blanks, or click blank then click option'
A<T>
B(T)
C[T]
D{T}
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or braces instead of angle brackets for generic parameters.
Forgetting to declare the generic parameter.
4fill in blank
hard

Fill both blanks to declare a generic function wrapInArray that takes a value and returns it inside an array.

Typescript
function wrapInArray[1](value: [2]): [2][] {
  return [value];
}
Drag options to blanks, or click blank then click option'
A<T>
BT
CU
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names for argument and return type.
Not declaring the generic parameter.
5fill in blank
hard

Fill all three blanks to declare a generic function merge that takes two objects and returns their merged result.

Typescript
function merge[1](obj1: [2], obj2: [3]): [2] & [3] {
  return { ...obj1, ...obj2 };
}
Drag options to blanks, or click blank then click option'
A<T, U>
BT
CU
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same generic type for both arguments.
Not declaring generic parameters properly.