MediumGenerics & Bounds💻 Output Question

extends constraint — keyof and property access

💡

Hint

The pattern <T, K extends keyof T>(obj: T, key: K): T[K] is one of TypeScript's most powerful generic signatures. It ensures property names are valid AND the return type matches the property type — no casting needed.

What does this output?

// Simulate T extends keyof U — type-safe property access
function getProperty(obj, key) {
  // TypeScript: T extends object, K extends keyof T, returns T[K]
  if (!(key in obj)) throw new Error('key not found');
  return obj[key];
}

const user = { name: 'Alice', age: 30, email: 'alice@example.com' };

console.log(getProperty(user, 'name'));
console.log(getProperty(user, 'age'));
console.log(typeof getProperty(user, 'age'));
console.log(typeof getProperty(user, 'name'));

// TypeScript ensures return type matches the property type
// getProperty(user, 'name') => string
// getProperty(user, 'age') => number

Correct Output

Alice
30
number
string

Why this output?

Explanation: getProperty with a K extends keyof T constraint returns T[K] — the exact type of the property accessed. TypeScript infers "Alice" returns string and 30 returns number.

Key Insight: The pattern (obj: T, key: K): T[K] is one of TypeScript's most powerful generic signatures. It ensures property names are valid AND the return type matches the property type — no casting needed.

More Generics & Bounds Output Questions

MediumGeneric identity — T resolves to the argument typeHardGeneric Array utilities — map and filter type resolutionHardConstrained generic with default — what type is inferred

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz