0
0
Typescriptprogramming~20 mins

Multiple generic parameters in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of Multiple Generic Parameters
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a function with two generic parameters
What is the output of the following TypeScript code?
Typescript
function pairToString<T, U>(first: T, second: U): string {
  return `${typeof first}:${first},${typeof second}:${second}`;
}

console.log(pairToString<number, string>(42, "hello"));
A"number:42,string:hello"
B"number, string"
C"42,hello"
D"T:42,U:hello"
Attempts:
2 left
💡 Hint
Look at how the function uses typeof to get the type names as strings.
Predict Output
intermediate
2:00remaining
Result of generic tuple type usage
What is the type of variable 'result' after this code runs?
Typescript
function makeTuple<A, B>(a: A, b: B): [A, B] {
  return [a, b];
}

const result = makeTuple<string, number>("age", 30);
Astring[]
B[number, string]
C[string, number]
Dany[]
Attempts:
2 left
💡 Hint
Check the return type annotation of the function.
🔧 Debug
advanced
2:00remaining
Identify the error in multiple generic parameters usage
What error does this TypeScript code produce?
Typescript
function combine<T, U>(a: T, b: U): T & U {
  return { ...a, ...b };
}

const result = combine<number, string>(5, "hello");
ATypeError: Cannot combine number and string
BSyntaxError: Unexpected token '&'
CNo error, result is {5, "hello"}
DTypeError: Spread types may only be created from object types
Attempts:
2 left
💡 Hint
Consider what types can be spread into objects.
📝 Syntax
advanced
2:00remaining
Correct syntax for multiple generic parameters in interface
Which option correctly declares an interface with two generic parameters T and U?
Ainterface Pair<T, U> { first: T; second: U; }
Binterface Pair<T> U { first: T; second: U; }
Cinterface Pair<T; U> { first: T; second: U; }
Dinterface Pair<T U> { first: T; second: U; }
Attempts:
2 left
💡 Hint
Generic parameters are separated by commas inside angle brackets.
🚀 Application
expert
3:00remaining
Determine output of complex generic function with constraints
What is the output of this TypeScript code?
Typescript
function mergeObjects<T extends object, U extends object>(obj1: T, obj2: U): T & U {
  return { ...obj1, ...obj2 };
}

const a = { name: "Alice" };
const b = { age: 25 };
const merged = mergeObjects(a, b);
console.log(merged.name + " is " + merged.age + " years old.");
A"undefined is 25 years old."
B"Alice is 25 years old."
CTypeError: Cannot read property 'name' of undefined
DSyntaxError: Unexpected token '&'
Attempts:
2 left
💡 Hint
Check how the function merges two objects and the constraints on generic types.