Typed Generics Example - How To Type A Generic That Is A Key Property

[!INFO]-
topic: πŸ¦’ TypeScript
links: Generic type parameters make your components reusable over a variety of types
source: TypeScript course by the native web
tags: #permanent-noteΒ #published

Last Modified: =dateformat(this.file.mtime, "MMM. dd, yyyy - HH:mm")


If you want to pass a generic object and the corresponding key properties into a function, you can extend the generic key to be a key of the corresponding object <TObject, TKey extends keyof TObject>.

const person = {
  firstName: 'Dana',
  lastName: 'Scully',
  age: 30,
  department: 'X-Files'
};

const getProperty = function <TObject, TKey extends keyof TObject> (obj: TObject, key: TKey) {
  return obj[key];
};

const firstName = getProperty(person, 'firstName');

export {};