简体   繁体   English

如何将Typescript与动态对象键一起使用

[英]How to use typescript with dynamic object key

I have a State object that records time in days, hours, and minutes. 我有一个State对象,以天,小时和分钟为单位记录时间。 I defined my state like this: 我这样定义状态:

type StateKeys = "days" | "hours" | "minutes";

type State = {
    [K in StateKeys]: number
};

Later, I want to set state based on a value changed in a control. 稍后,我想根据控件中更改的值设置状态。 There are three controls, one for day, another for hours, and a third for minutes. 有三个控件,一个控件用于一天,另一个控件用于小时,第三个控件用于分钟。 I have one handler function that is hooked up to each of these controls. 我有一个处理程序函数与每个控件挂钩。 Here's an excerpt of that function: 这是该函数的摘录:

_onTimeComponentChange(e: any) {
    const name : StateKeys = e.currentTarget.name;
    const updatedValue = parseInt(e.currentTarget.value);
    this.setState(
        //@ts-ignore
        {[name]: updatedValue}, 
        () => {
            this.updateValue();
        }
    )
}

My goal is to remove the //@tsignore comment. 我的目标是删除//@tsignore评论。 If I do that now, I get this error message: 如果现在执行此操作,则会收到以下错误消息:

Argument of type '{ [x: string]: number; 类型'{[x:string]:number; }' is not assignable to parameter of type 'State | }'不可分配给'State | ((prevState: Readonly, props: Readonly) => State | Pick) | ((prevState:只读,props:只读)=>状态|选择)| Pick'. 挑'。 Type '{ [x: string]: number; 输入'{[x:string]:数字; }' is missing the following properties from type 'Pick': days, hours, minutes }”缺少类型“选择”中的以下属性:天,小时,分钟

How do I remove the //@tsignore comment and satisfy typescript's requirements? 如何删除//@tsignore注释并满足打字稿的要求?

It's definitely hard to get around this type of thing without casting. 如果不进行强制转换,绝对很难解决这类问题。 You can try following the pattern described here : 您可以尝试遵循此处描述的模式:

updateState(key: StateKeys, value: string) {
  this.setState((prevState) => ({
    ...prevState,
    [key]: value,
  }));
}

which would look like: 看起来像:

_onTimeComponentChange(e: any) {
  const name: StateKeys  = e.currentTarget.name
  const updatedValue = parseInt(e.currentTarget.value)
  this.setState(
    prevState => ({
      ...prevState,
      [name]: updatedValue,
    }),
    () => {
    },
  )
}

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

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