Generic Constraints On Keys
Constrain generic parameters with keyof so a helper can only be called with real property names, and the return type follows the key.
Code
function pluck<T, K extends keyof T>(rows: T[], key: K): T[K][] {
return rows.map((row) => row[key]);
}
interface User {
id: number;
name: string;
active: boolean;
}
const users: User[] = [
{ id: 1, name: 'ada', active: true },
{ id: 2, name: 'bob', active: false },
];
// 返回类型自动跟随 key:number[] / string[] / boolean[]
const ids = pluck(users, 'id');
const names = pluck(users, 'name');
console.log(ids, names);
// 不存在的键是编译错误
// pluck(users, 'email');
// 约束也能限定"必须可排序"
function sortBy<T, K extends keyof T>(rows: T[], key: K): T[] {
return [...rows].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0));
}
console.log(sortBy(users, 'name').map((u) => u.name));Output
Captured from a sandboxed run of this snippet in the build pipeline.
[ 1, 2 ] [ 'ada', 'bob' ]
[ 'ada', 'bob' ]What the snippet does
Two helpers carry the behavior: pluck and sortBy — everything else is wiring.
It builds and returns a fresh value rather than reusing its inputs.
Statements that matter
return [...rows].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0));
return rows.map((row) => row[key]);
Interactive Tools for This Topic
FAQ
- Does `pluck` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `pluck`, `sortBy` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.