"Object is possibly undefined" in for observable field

TyForHelpDude picture TyForHelpDude · Feb 17, 2017 · Viewed 7.4k times · Source

Retrieve data and set obseravble array, here is code below:

import {observable} from 'mobx';

export interface IMenuModel{
    Id:number
    itemName:string;
    parentId?:number;    
}
 class MenuRepo {
    @observable menuItems? : IMenuModel[];
    constructor(){
    }
    getItems():void {
    fetch(`..`).then((response: Response): Promise<{ value:IMenuModel[] }>  => {
              return response.json();
            })
             .then((response: { value: IMenuModel[] }) : void => {
               this.menuItems = response.value;

      }, (error: any): void => {
        //exception handling
      });
    }
}

var menuCodes = new MenuRepo
export default menuCodes;

this is the observer class;

import * as React from 'react';
import {observer} from 'mobx-react';
import {IMenuModel} from './Codes';

@observer
class Menu extends React.Component<{params?:IMenuModel[]}, {}> {
  render() {
    debugger
    var menuJSX : JSX.Element[] = this.props.params.map((item:IMenuModel, i:number)=>{
      return (<li key={item.Id}>{item.itemName}</li>)
    });
    return (
      <div>
        Hello World!!!!
        <br />
        {menuJSX}
      </div>
    );
  }
}
export default Menu;

Also I encounter error above("this.props.params" underlined red): Object is possibly 'undefined'

Couldnt figure how to fix it.. and this is main component;

import menuCodes from './components/Codes';
    class App extends React.Component<null, null> {
      render() {
        return (
          <div className="App">
            <Menu params = {menuCodes.menuItems}/>
          </div>
        );
      }
    }

Answer

Yo Wakita picture Yo Wakita · Feb 17, 2017

This is a Typescript specific error I believe.

Your params prop in your Menu component is optional. So, I am assuming that in your MenuCodes component, menuCodes.menuItems may be undefined at times.

If you are mapping over this.props.params, and it may be undefined at some point, you need to include a conditional in the assignment of your menuJSX variable to account for when menuCodes.menuItems (and thus props.params) is undefined.

Something like this ternary:

const { params } = this.props
var menuJSX : JSX.Element[] = params 
  ? params.map((item:IMenuModel, i:number) =>
    <li key={item.Id}>{item.itemName}</li>
  )
  : [];