React事件处理程序中带有Typescript的动态对象键

Car*_*llo 4 typescript reactjs

类似但不同于如何在TypeScript中为对象动态分配属性?

我有一个状态类型的组件:

{
  low: string
  high: string
}
Run Code Online (Sandbox Code Playgroud)

和React中的常见模式一样,我的事件处理程序是:

handleChange = (e) => {
  let { name, value } = e.target;
  this.setState({ [name]: value });
};
Run Code Online (Sandbox Code Playgroud)

使用highlow作为name我输入的属性.打字稿错误:

Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'Pick<State, "low" | "high">'

有没有办法让我告诉Typescript我只期望那两个值?我想避免显式将密钥传递给处理程序,但不希望将状态更改为:

{
  low: string
  high: string
  [key: string]: string
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*mid 13

在完美的世界中,我们应该能够写出这样的东西:

private handleChange = (e: {target: {name: "low" | "high", value: string}}) =>
{
    const { name, value } = e.target;

    this.setState({[name]: value});
}
Run Code Online (Sandbox Code Playgroud)

但不幸的是,报告的错误(请参阅此处此处)迫使我们使用一些临时解决方法,例如转换为任何或类似的:

this.setState({[name]: value} as any);
Run Code Online (Sandbox Code Playgroud)