0
0
Typescriptprogramming~20 mins

Generic function syntax in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generic Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a generic identity function
What is the output of this TypeScript code when calling identity(42)?
Typescript
function identity<T>(arg: T): T {
  return arg;
}

console.log(identity(42));
Aundefined
B"42"
C42
DTypeError
Attempts:
2 left
💡 Hint
The function returns exactly what it receives.
Predict Output
intermediate
2:00remaining
Output of generic function with array argument
What will this code print to the console?
Typescript
function firstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

console.log(firstElement(['apple', 'banana', 'cherry']));
A"banana"
B"apple"
Cundefined
DTypeError
Attempts:
2 left
💡 Hint
The function returns the first item of the array.
Predict Output
advanced
2:00remaining
Output of generic function with multiple type parameters
What is the output of this code?
Typescript
function pairToString<K, V>(key: K, value: V): string {
  return `${key}: ${value}`;
}

console.log(pairToString<number, string>(1, "one"));
A"1: one"
B"one: 1"
C"[object Object]: one"
DTypeError
Attempts:
2 left
💡 Hint
The function formats key and value as a string separated by a colon.
Predict Output
advanced
2:00remaining
Output of generic function with constraints
What will this code output?
Typescript
interface Lengthwise {
  length: number;
}

function loggingLength<T extends Lengthwise>(arg: T): number {
  return arg.length;
}

console.log(loggingLength('hello'));
A5
B"hello"
CTypeError
Dundefined
Attempts:
2 left
💡 Hint
Strings have a length property.
🧠 Conceptual
expert
3:00remaining
Type inference in generic functions
Given the generic function function wrap(value: T): { value: T }, what is the inferred type of T when calling wrap([1, 2, 3])?
Aunknown
Bnumber
Cany[]
Dnumber[]
Attempts:
2 left
💡 Hint
The type parameter matches the argument's type exactly.