Typescript & React 中 setState 数据定义的问题

描述

React 编写的页面中有很多表单填写的 input,原本都是用如下的内容来编写:

state = {
    mobile: '',
    smsCaptcha: '',
    passWord: '',
    otherState: 0,
}

handleInput = (key, value) => {
    this.setState({
      [key]: value
    })
}

render() {
    return (
        <div>
            <input
                type='tel'
                maxLength={11}
                value={mobile}
                placeholder='请输入手机号'
                onChange={event => this.handleInputChange('mobile', event.target.value) }
            />
            <input
                type='number'
                value={smsCaptcha}
                placeholder='请输短信验证码'
                onChange={event => this.handleInputChange('smsCaptcha', event.target.value) }
            />
            ...
       </div>
    )
}

现在需要将原始的项目使用 ts 重写

首先 state 的 interface 各个属性中有存在不是 string 的类型:

interface IState {
    mobile: string
    smsCaptcha: string
    passWord: string
    otherState: number
}

现在需要给 handleInput 方法加上 typescript 验证:

handleInput = (key: string, value: string) => {
    this.setState({
      [key]: value
    })
}

上面的写法会导致错误:

Argument of type '{ [x: string]: string; }' is not assignable to parameter of type ...

即便我想办法获取了当前 state 的 interface 中所有可以是 string 的类型 也不行:

handleInput = (key: 'mobile' | 'smsCaptcha' | 'passWord', value: string) => {
    this.setState({
      [key]: value
    })
}

有什么比较好的方案么?

阅读 11.5k
4 个回答

四处用 any 的话引入 ts 就没有意义了。ts 这里已经提醒了你有潜在的问题,应该对输入的数据进行处理,提供一种思路供参考。

  handleInput = (key: keyof IState, value: number | string) => {
    if (key === 'otherState' && typeof value === 'number') {
      this.setState({
        otherState: value
      })
    } else if (key !== 'otherState' && typeof value === 'string') {
      this.setState({
        [key]: value
      } as Pick<IState, typeof key>)
    } else {
      // 错误处理
    }
  }
handleInput = (key: keyof IState, value: string | number) => {
    this.setState({
      [key]: value
    } as Pick<IState, keyof IState>)
}
新手上路,请多包涵

首先从 interface IState 获取 key 的集合
type StateName = keyof IState;
定义handleInput函数时,如下
handleInput = (key: StateName, value: string | number) => {this.setState({ [key]: value }) }

推荐问题