// Pick a property by key, preserving its exact type.
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 42, name: 'Alice' };
const id = getProp(user, 'id'); // number
const name = getProp(user, 'name'); // string
// getProp(user, 'zzz'); // ✗ "zzz" is not in keyof user
// Constraint to a shape:
function hasId<T extends { id: unknown }>(x: T): boolean {
return x.id !== null && x.id !== undefined;
}
hasId({ id: 1, name: 'a' }); // ✓
hasId({ name: 'a' }); // ✗ missing `id`
Create a free account and build your private vault. Share publicly whenever you want.