// Created on savesnippets.com ยท https://savesnippets.com/ycBgaMdh8tiYCV // Pick a property by key, preserving its exact type. function getProp(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(x: T): boolean { return x.id !== null && x.id !== undefined; } hasId({ id: 1, name: 'a' }); // โœ“ hasId({ name: 'a' }); // โœ— missing `id`