Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
Generic functions use angle brackets
<> to declare type parameters.2fill in blank
mediumComplete 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'
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.
✗ Incorrect
When calling a generic function, specify the type argument inside angle brackets.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses or braces instead of angle brackets for generic parameters.
Forgetting to declare the generic parameter.
✗ Incorrect
Generic parameters must be declared inside angle brackets after the function name.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names for argument and return type.
Not declaring the generic parameter.
✗ Incorrect
Declare the generic parameter
<T> and use T as the type for the argument and return array.5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same generic type for both arguments.
Not declaring generic parameters properly.
✗ Incorrect
Declare two generic parameters
<T, U> and use them as types for the two arguments and the return type as their intersection.