0
0
Typescriptprogramming~20 mins

How TypeScript infers generic types - Practice Exercises

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

console.log(identity(42));
A42
B"42"
Cundefined
DType error at compile time
Attempts:
2 left
💡 Hint
TypeScript infers the generic type from the argument passed.
Predict Output
intermediate
2:00remaining
What type does TypeScript infer here?
Given this function call, what type does TypeScript infer for T?
Typescript
function wrapInArray<T>(value: T): T[] {
  return [value];
}

const result = wrapInArray('hello');
Anever[]
Bstring[]
Cany[]
Dnumber[]
Attempts:
2 left
💡 Hint
Look at the argument passed to the function.
Predict Output
advanced
2:00remaining
What is the output of this generic function with multiple parameters?
What will this code print when run?
Typescript
function merge<T, U>(obj1: T, obj2: U): T & U {
  return {...obj1, ...obj2};
}

const merged = merge({name: 'Alice'}, {age: 30});
console.log(merged);
AType error: incompatible types
B{ name: 'Alice' }
C{ age: 30 }
D{ name: 'Alice', age: 30 }
Attempts:
2 left
💡 Hint
The function combines two objects using spread syntax.
Predict Output
advanced
2:00remaining
What error does this code raise due to incorrect generic inference?
What error will this TypeScript code produce?
Typescript
function firstElement<T>(arr: T[]): T {
  return arr[0];
}

const result = firstElement([]);
console.log(result);
AType error: Argument of type 'never[]' is not assignable to parameter of type 'T[]'.
BError: Element implicitly has an 'any' type because type '[]' has no elements.
Cundefined
Dnull
Attempts:
2 left
💡 Hint
TypeScript infers the empty array as never[], causing a type mismatch.
🧠 Conceptual
expert
3:00remaining
Which option best describes how TypeScript infers generic types in this scenario?
Given a generic function with multiple parameters, how does TypeScript infer the generic types when called with different argument types?
ATypeScript requires explicit generic type annotations when multiple parameters have different types.
BTypeScript infers the generic types by using the first argument's type for all generic parameters.
CTypeScript infers each generic type parameter independently based on the corresponding argument's type.
DTypeScript cannot infer generic types if there are multiple parameters and throws a compile error.
Attempts:
2 left
💡 Hint
Think about how TypeScript matches each generic parameter to each argument.