Home > Back-end >  Property length does not exist on type string | number | {}[]
Property length does not exist on type string | number | {}[]

Time:11-24

Here is the type of the variable

type imageTags: string | number | {
    tag_type: string;
    tag_name: string;
    tag_id: number;
    photo_id: number;
    confidence: number;
}[]

This is how i try to access its properties.

    if (imageTags.length > 0) {
      return imageTags[0].tag_name === image_type;
    }

The variable can be a string , number or array then why am I getting the error Property 'length' does not exist on type 'string | number | { tag_type: string; tag_name: string; tag_id: number; photo_id: number; confidence: number; }[]'. Property 'length' does not exist on type 'number'.ts(2339)

CodePudding user response:

imageTags is declared as either string, number, or an array of objects. Maybe you expected it to be an array of string, number and/or objects instead, so that it's always an array? Then you should use parentheses:

type imageTags: (string | number | {
    tag_type: string;
    tag_name: string;
    tag_id: number;
    photo_id: number;
    confidence: number;
})[]

CodePudding user response:

You could check if imageTags's type is Array and only then check the length:

if (Array.isArray(imageTags) && imageTags.length) {
  return imageTags[0].tag_name === image_type;
}
  • Related