简体   繁体   中英

How to use Typescript Generics in modifier functions

I am looking for a way to correctly strong type a below case, I suspect i need to use Typescript Generics in this situation.

interface Person {
  name: string;
  age: number;
}

const person: Person = {
  name: "John",
  age: 30,
};

const alterPerson = (key: keyof Person, val) => {
  person[key] = val;
}

My intention is that function 'alterPerson' is aware it can only take Person keys as its first argument and then, once it has taken a key i want the function to know what type of value can be assigned to that key.

Can you show me how this could be done. Thank you!

alterPerson is still directly coupled to the person variable. To make this truly reusable with generics, you'd need to also pass that variable as a function parameter.

const alterObject = <T>(object: T, key: keyof T, val: T[keyof T]) => {
  object[key] = val;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM