allow typescript compiler to call setState on only one react state property

前端 未结 5 2074
半阙折子戏
半阙折子戏 2020-12-13 06:17

I\'m using Typescript with React for a project. The Main component gets passed state with this interface.

interface MainState {
  todos: Todo[];
  hungry: B         


        
5条回答
  •  -上瘾入骨i
    2020-12-13 07:04

    We can tell setState which field it should expect, by parametrising it with <'editorState'>:

    this.setState<'editorState'>({
      editorState: editorState
    });
    

    If you are updating multiple fields, you can specify them like this:

    this.setState<'editorState' | 'hungry'>({
      editorState: editorState,
      hungry: true,
    });
    

    although it will actually let you get away with specifying only one of them!

    Anyway with the latest TS and @types/react both of the above are optional, but they lead us to...


    If you want to use a dynamic key, then we can tell setState to expect no fields in particular:

    this.setState({
      [key]: value,
    });
    

    and as mentioned above, it doesn't complain if we pass an extra field.

    (GitHub issue)

提交回复
热议问题