// 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// 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: 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