Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Object is possibly undefined" in for observable field

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>
        );
      }
    }
like image 918
TyForHelpDude Avatar asked Feb 17 '17 15:02

TyForHelpDude


People also ask

How do you fix possibly undefined object?

The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.

How do you handle undefined in TypeScript?

To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined. We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.

How do I ignore undefined TypeScript?

You can use the non-null assertion operator in TypeScript to take a typed variable and remove the undefined and null types from it.


1 Answers

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>
  )
  : [];
like image 187
Yo Wakita Avatar answered Sep 28 '22 00:09

Yo Wakita