0
0
Typescriptprogramming~20 mins

Generic arrow functions in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generic Arrow Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a generic arrow function with array input
What is the output of this TypeScript code using a generic arrow function that returns the first element of an array?
Typescript
const firstElement = <T>(arr: T[]): T => arr[0];

console.log(firstElement([10, 20, 30]));
AError at compile time
B20
C10
Dundefined
Attempts:
2 left
💡 Hint
The function returns the first item of the array passed in.
Predict Output
intermediate
2:00remaining
Output of generic arrow function with object type
What will this TypeScript code output when using a generic arrow function to get a property value from an object?
Typescript
const getProp = <T, K extends keyof T>(obj: T, key: K): T[K] => obj[key];

const person = { name: 'Alice', age: 30 };
console.log(getProp(person, 'name'));
A"Alice"
B30
Cundefined
DType error at compile time
Attempts:
2 left
💡 Hint
The function returns the value of the given key from the object.
🔧 Debug
advanced
2:00remaining
Identify the error in this generic arrow function
This TypeScript generic arrow function is intended to swap two elements in a tuple. What error will it produce?
Typescript
const swap = <T, U>(pair: [T, U]): [U, T] => {
  return [pair[1], pair[0]];
};

const result = swap([true, 42]);
console.log(result);
AType error: Cannot infer type parameters
BSyntax error: missing return type annotation
CRuntime error: undefined is not iterable
DNo error, outputs [42, true]
Attempts:
2 left
💡 Hint
Check if the function correctly swaps tuple elements and returns the expected type.
📝 Syntax
advanced
2:00remaining
Which option has correct syntax for a generic arrow function?
Which of the following is the correct syntax for a generic arrow function in TypeScript that returns the length of an array?
Aconst length = (arr: T[]) => arr.length;
Bconst length = <T>(arr: T[]) => arr.length;
Cconst length = <T>(arr: Array) => arr.length;
Dconst length = <T>(arr: T[]) => { arr.length }
Attempts:
2 left
💡 Hint
Generic type parameters must be declared before the function parameters.
🚀 Application
expert
3:00remaining
Using generic arrow function to merge two objects
Given this generic arrow function to merge two objects, what is the type of the returned object when merging {a: 1} and {b: 'x'}?
Typescript
const merge = <T, U>(obj1: T, obj2: U): T & U => ({ ...obj1, ...obj2 });

const merged = merge({ a: 1 }, { b: 'x' });
A{ a: number; b: string; }
B{ b: string; }
C{ a: number; }
DError: Cannot merge objects of different types
Attempts:
2 left
💡 Hint
The returned type combines properties from both input objects.