简体   繁体   English

如何在修饰函数中使用 Typescript Generics

[英]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.我正在寻找一种正确强类型以下情况的方法,我怀疑在这种情况下我需要使用 Typescript Generics。

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.我的意图是 function 'alterPerson' 知道它只能将 Person 键作为其第一个参数,然后,一旦它使用了一个键,我希望 function 知道可以为该键分配什么类型的值。

Can you show me how this could be done.你能告诉我如何做到这一点。 Thank you!谢谢!

alterPerson is still directly coupled to the person variable. alterPerson仍然直接耦合到person变量。 To make this truly reusable with generics, you'd need to also pass that variable as a function parameter.为了使 generics 真正可重用,您还需要将该变量作为 function 参数传递。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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