Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a generic function that returns the input value.
Typescript
function identity<T>([1]: T): T { return [1]; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a parameter name that doesn't match the return statement.
Using a non-generic type.
✗ Incorrect
The generic function uses a parameter named 'value' of type T and returns it.
2fill in blank
mediumComplete the code to call the generic function with a string argument and let TypeScript infer the type.
Typescript
const result = identity([1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a number or boolean instead of a string.
Passing null which is not inferred as a string.
✗ Incorrect
Passing a string literal 'hello' lets TypeScript infer T as string.
3fill in blank
hardFix the error in the generic function call by specifying the type explicitly.
Typescript
const result = identity<[1]>(42);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Specifying a type that doesn't match the argument type.
Omitting the generic type when explicit specification is needed.
✗ Incorrect
Explicitly specifying 'number' as the generic type matches the argument 42.
4fill in blank
hardFill both blanks to define a generic function that returns the length of an array of generic type T.
Typescript
function getLength<[1]>(arr: [2][]): number { return arr.length; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names for the parameter and array element.
Not using a generic type for the array elements.
✗ Incorrect
The generic type parameter is T, and the array parameter is of type T[].
5fill in blank
hardFill all three blanks to create a generic function that returns the first element of an array of generic type T or undefined if empty.
Typescript
function firstElement<[1]>(arr: [2][]): [3] | undefined { return arr.length > 0 ? arr[0] : undefined; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type names for parameters and return type.
Not including undefined in the return type.
✗ Incorrect
The generic type parameter is T, the array is of type T[], and the return type is T or undefined.