azazdeaz
azazdeaz

Reputation: 113

How to create TypeScript types for a function that calls React setState with its arguments?

This doesn't work because Partial<IState> returns a type that can have undefineds as values which are not acceptable by setState.

interface IState {
  bar: number
  baz: boolean
}

class App extends React.Component<{}, IState> {
  constructor(props) {
    super(props)
    this.state = {
      bar: 123,
      baz: false,
    }
  }
  public render() {
    return null
  }
  public update(options: Partial<IState>) {
    this.setState(options)
  }
  public callUpdate() {
    this.update({ bar: 4 })
  }
}

The only solution i found is to add the current state to the setState as well:

this.setState({  ...this.state, ...options })

Is there any better way to do this?

typescript version: 3.2.1

Upvotes: 2

Views: 158

Answers (2)

Peter Ambruzs
Peter Ambruzs

Reputation: 8213

If you are sure that option is never undefined you can add an exclamation mark after the option that is the non null assertion operator.

  public update(options: Partial<IState>) {
    this.setState(options!)
  }

An I want to point out, that using this.setState({ ...this.state, ...options }) can result data loss. Because this.state is not updated until the next render. If you want to use the current state you should use this.setState(state => ({...state, ...options}) instead.

Upvotes: 0

Thanh Le Hai Hoang
Thanh Le Hai Hoang

Reputation: 1403

You may want to use Type Assertion:

this.setState(options as IState)

Using this.setState({ ...this.state, ...options }) is not recommended because you have to destructure the current state object, which is unnecessary

Upvotes: 1

Related Questions