Challenge - 5 Problems
Generic Constraints Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of generic function with extends constraint
What is the output of the following TypeScript code?
Typescript
function getLength<T extends { length: number }>(arg: T): number { return arg.length; } console.log(getLength('hello')); console.log(getLength([1, 2, 3]));
Attempts:
2 left
💡 Hint
Remember that both strings and arrays have a length property.
✗ Incorrect
The function getLength accepts any argument with a length property. 'hello' has length 5, and the array has length 3, so the outputs are 5 and 3.
🧠 Conceptual
intermediate1:30remaining
Understanding extends in generic constraints
Which statement best describes the role of
extends in the generic constraint T extends { length: number }?Attempts:
2 left
💡 Hint
Think about what types can be passed to a function requiring a length property.
✗ Incorrect
The extends keyword in generic constraints restricts the generic type to those that have at least the specified properties. Here, T must have a length property of type number.
🔧 Debug
advanced2:30remaining
Identify the error in generic constraint usage
What error does this TypeScript code produce?
Typescript
function copyFields<T, U extends T>(target: T, source: U): T { for (const id in source) { target[id] = source[id]; } return target; } const x = { a: 1, b: 2 }; const y = { a: 1, b: 3, c: 4 }; copyFields(x, y);
Attempts:
2 left
💡 Hint
Check the properties of the objects and the generic constraints.
✗ Incorrect
The function expects source (U) to extend target (T), but y has property 'c' which x does not. Assigning source[id] to target[id] causes an error because 'c' is not in T.
📝 Syntax
advanced2:00remaining
Correct generic constraint syntax
Which option correctly declares a generic function that accepts only objects with a
name property of type string?Attempts:
2 left
💡 Hint
Remember the correct syntax for generic constraints in TypeScript.
✗ Incorrect
Option A uses the correct syntax:
T extends { name: string }. Other options use invalid or non-TypeScript syntax.🚀 Application
expert3:00remaining
Determine the output of complex generic constraint usage
What is the output of this TypeScript code?
Typescript
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
const result = loggingIdentity({ length: 10, value: 3 });
console.log(result.value);Attempts:
2 left
💡 Hint
Consider how TypeScript infers the type of the argument and the return value.
✗ Incorrect
The argument has length and value properties, so T is inferred as { length: number; value: number }. The function logs 10, then returns the object, so result.value is 3.