简体   繁体   English

Typescript 接口特定的属性设置函数

[英]Typescript interface specific property set function

I have an interface "Example" and I want to create a function that will get key (name of property from Example) and new value for that key.我有一个接口“示例”,我想创建一个函数来获取键(来自示例的属性名称)和该键的新值。 But i don't understand how to write types for that, now I code smth but this is not work.但我不明白如何为此编写类型,现在我编写了 smth 代码,但这不起作用。

interface Example {
  num: number;
  str: string;
}

const obj: Example = {
  num: 5,
  str: '123'
}

const setExampleProp = ({key, value}: {
  key: keyof Example;
  value: Example[keyof Example];
}) => {
  obj[key] = value
}

Error: Type 'string |错误:键入 'string | number' is not assignable to type 'never'. number' 不能分配给类型 'never'。 Type 'string' is not assignable to type 'never'.类型 'string' 不能分配给类型 'never'。

Change it to a generic function将其更改为通用函数

function setExampleProp<T extends keyof Example>({key, value}: {
  key: T;
  value: Example[T];
}) {
  obj[key] = value
}

The answer above is valid.上面的答案是有效的。

Another approach would be to add a index signature to your interface:另一种方法是向您的界面添加索引签名:

interface Example {
  num: number;
  str: string;

  [name: string]: Example[keyof Example];
}

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

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