1

I am studying Typescript with React and MobX.

My MobX Store likes blew.

store: {
  child: {
    selected: true,
    value: 123
  }
}

My Component is

@inject('store')
@observer
class Display extends React.Component<{store: Object}, {}> {
  ...

  render(){
    console.log(this.props.store.child.selected); // true
  }
}

and I can see this alert.

[ts] Property 'child' does not exist on type 'Object'. [2339]

kyun
  • 8,693
  • 8
  • 27
  • 56

2 Answers2

2

You can use interfaces to declare the shapes of store:

interface Child {
    selected: boolean;
    value: number;
}

interface Store {
    child: Child;
}

@inject('store')
@observer
class Display extends React.Component<{ store: Store }, {}> {
  ...

  render() {
    console.log(this.props.store.child.selected); // true
  }
}

Or you can use either any or unknown for the store type.

Dor Shinar
  • 1,334
  • 1
  • 10
  • 15
2

The error you're getting is because you're defining your store prop as a generic Object, which doesn't have a property called child.

To make it work, just define an interface for your store like so:

interface Store {
  store: {
    child: {
      selected: boolean;
      value: number;
    }
  }
}

And then use that as definition for the props in the component as such:

class Display extends React.Component<Store, {}> {

bamtheboozle
  • 4,399
  • 2
  • 15
  • 29