简体   繁体   中英

Object is possibly 'undefined'. TS2532

I keep getting Object is possibly 'undefined'. TS2532 and I know that it's due to assignment of setViewer to undefined, which I have done for the purpose of login matching but I came across with another problem. Right now, I have 2 data coming in homeviewer and one of them is announcements and when I try to access the data, it gives me TS2532 error. Here are the code below. I am new to these and I don't know what to change for the setViewer ( setViewer: () => undefined ) in order it for to work.

homeViewer.ts

import { createContext } from 'react';

import { HomeViewer } from '../types/home_viewer';

export interface ViewerContextType {
  viewer?: HomeViewer;
  setViewer: (home: HomeViewer) => void;
}

export const ViewerContext = createContext<ViewerContextType>({
  viewer: {},
  setViewer: () => undefined,
});

That takes interface from

export interface HomeViewer {
  user?: User;
  announcements?: Announcement;
}

The part where I use it

const { viewer } = useContext(ViewerContext);

  const data = viewer?.announcements;

  console.log(data[0]);

If I understand correctly, your issue is revolving around accessing elements at specific indexes from data – where data possibly has a value of undefined (as per your HomeViewer interface);

export interface HomeViewer {
 user?: User;
 announcements?: Announcement;
}

To me, it appears that the Announcement type is indicative of an array of some elements (judging by the way you're accessing its data), or undefined (since it's optional).

Meaning, it will never certainly be an instance of Announcement 's type declaration, so you'll have to chain an optional access operator for accessing array elements that possibly don't exist: ?. ;

const { viewer } = useContext(ViewerContext);
const data = viewer?.announcements;

console.log(data?.[0]) // -> Ok!
console.log(data[0])  //  -> Err! Object is possibly undefined.

It could be because if viewer is undefined then data will also be undefined , and you can't do data[0] because is the same as undefined[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM