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
  • 9,710
  • 9
  • 31
  • 66
  • 2
    I think you are looking for `class Display extends React.Component<{store: child: { selected: boolean, value: number } }, {}>` – Titian Cernicova-Dragomir Feb 01 '19 at 10:53
  • @TitianCernicova-Dragomir Oh... is it the only way to solve it? – kyun Feb 01 '19 at 10:55
  • 1
    `store: any` would be the other but that basically breaks out of type safety altogether and I don't recommend it – Titian Cernicova-Dragomir Feb 01 '19 at 10:57
  • It is actually very logical. `Object` type doesn't have `child` property inside it. To make it work, you could define your type more explicitly, or just pass `store: any` (but please don't, I assume you are not using TypeScript to ignore typing) – Piotr Szlagura Feb 01 '19 at 10:58

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,474
  • 2
  • 11
  • 17
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
  • 5,847
  • 2
  • 17
  • 31