1

i have a type ImageType and incoming props from parent, it can be an Object or Array of Objects. I'm cheking if prop is Object then get directly access the "src" property but as you can see i'm getting an error from typescript. Any idea how to solve ? Thanks

type Props = {
  label?: string;
  value: ImageType[] | ImageType;
  multiple: boolean;
  cls?: string;
  getValue: (val: ImageType[]) => void;
  folderInCloud: string;
  [key: string]: any;
};

type ImageType = {
  src: string;
  alt: string;
};

enter image description here

mirik999
  • 349
  • 3
  • 8

1 Answers1

0

The reason TypeScript is returning that error is because it cannot narrow the type because arrays are objects. You can modify the condition to use Array.isArray() instead.

Calvin
  • 443
  • 3
  • 7
  • didn't help, the same ts error exists. if (Array.isArray(prev.value) && Array.isArray(next.value)) .... – mirik999 Jun 19 '21 at 18:15
  • 1
    Are you not negating the check? An array does not, in fact, have a `src` property, so you would need `if (!Array.isArray(prev.value))`. Note the !. Unless you refactored the content within the if block. – futur Jun 19 '21 at 18:32
  • @ftrsk is correct, you can just negate the `Array.isArray()` calls (probably both of them), depending on how your `compareDeeper()` function is implemented. – Calvin Jun 19 '21 at 19:22