Flow: Optional state property in react component got an error when setState with null

Created on 20 Nov 2017  路  2Comments  路  Source: facebook/flow

/* @flow */

import React, { Component } from 'react'

type State = {
  someKey?: string,
}

class A extends Component<{}, State> {
  setSomething() {
    this.setState({ someKey: 'a' }) 
  }

  setNull() {
    this.setState({ someKey: null }) 
  }
}

Expected result: no errors
Actual result:

15:     this.setState({ someKey: null }) 
                      ^ object literal. This type is incompatible with the expected param type of
[LIB] static/v0.59.0/flowlib/react.js:35:     partialState: $Shape<State> | ((State, Props) => $Shape<State> | void),
                                                            ^ union: State | function type

However, if I modify State type to

type State = {
  someKey: ?string,
}

It passes.
I thought the question mark is supposed to be after the property name (like when you define prop types).
Is this a bug or the question mark is supposed to be before type of state property?
Please advise, thank you.

Flow version 0.59.0
flow.org/try

Most helpful comment

type A = { prop?: T } means that object can have prop of type T or do not have it at all.
type B = { prop: ?T } means that object always have prop, it can be of type T or null.
type C = { prop?: ?T } means that object can have prop, it can be of type T or null or do not have prop at all.

All 2 comments

type A = { prop?: T } means that object can have prop of type T or do not have it at all.
type B = { prop: ?T } means that object always have prop, it can be of type T or null.
type C = { prop?: ?T } means that object can have prop, it can be of type T or null or do not have prop at all.

I see, that explains a lot, thank you.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bennoleslie picture bennoleslie  路  3Comments

pelotom picture pelotom  路  3Comments

mmollaverdi picture mmollaverdi  路  3Comments

ctrlplusb picture ctrlplusb  路  3Comments

Beingbook picture Beingbook  路  3Comments