MediumGeneric Constraints🐛 Debug Challenge

Missing keyof constraint — unsafe property access

Buggy Code — Can you spot the issue?

// TypeScript without constraint: pluck<T>(items: T[], key: string): any[]
// Bug: accepts ANY string as key — invalid keys return undefined silently

function pluck(items, key) {
  return items.map(item => item[key]);
}

const users = [
  { name: 'Alice', age: 30 },
  { name: 'Bob',   age: 25 },
];

// Valid key — works
const names = pluck(users, 'name');
console.log(names.join(','));

// Invalid key — returns undefined silently (no TypeScript error without constraint)
const emails = pluck(users, 'email');
console.log(emails.join(','));  // ",," — undefined stringified

Fixed Code

// Fix: add K extends keyof T constraint — only valid keys accepted
// TypeScript: function pluck<T, K extends keyof T>(items: T[], key: K): T[K][]

function pluck(items, key) {
  // With K extends keyof T, TypeScript rejects invalid keys at compile time
  return items.map(item => item[key]);
}

const users = [
  { name: 'Alice', age: 30 },
  { name: 'Bob',   age: 25 },
];

// Fix: only use valid keys
const names = pluck(users, 'name');
console.log(names.join(','));

const ages = pluck(users, 'age');
console.log(ages.join(','));

Bug Explained

Bug: Without K extends keyof T constraint, any string key is accepted. Invalid keys (like "email") return undefined for each item — producing an array of undefined values with no compile-time warning.

Explanation: Using only valid keys (name, age) ensures all values are defined. The TypeScript fix (K extends keyof T) makes invalid keys a compile error — preventing the silent undefined bug.

Key Insight: The signature (items: T[], key: K): T[K][] is three guarantees in one: K must be a real key of T, the return type T[K] matches the property type, and TypeScript prevents typos in key names.

More Generic Constraints Debug Challenges

HardMissing extends object constraint — primitive passed to object utilityHardGeneric function returns any instead of constrained type

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab