1

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)

Amos Machora
  • 486
  • 3
  • 12
  • 4
    "*The variable can be a string , number or array then why am I getting the error*" numbers don't have a `.length` property. Or as the error message says: "Property 'length' does not exist on type 'number'" I don't see what you expect other than somebody re-stating what the error message says. – VLAZ Nov 24 '22 at 09:12
  • Not sure what you're expecting as an answer, but the error clearly states that `number` does not have a property `length`. (I also assume you don't actually want to access `string` like that, too ;) ) –  Nov 24 '22 at 09:25
  • @VLAZ i found the fix to my problem on one of the answers to this questions. However is there a way for me to check if the value is actually an array then access the length property ? – Amos Machora Nov 24 '22 at 09:32
  • [How do I check if a variable is an array in JavaScript?](https://stackoverflow.com/q/767486) | [Test for array of string type in TypeScript](https://stackoverflow.com/q/23130292) | [How do you check if a type is an array?](https://stackoverflow.com/q/71623415) – VLAZ Nov 24 '22 at 09:34

2 Answers2

2

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;
}
Rachel
  • 129
  • 5
1

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;
})[]
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • this worked. However is there a more elegant way for me to write the if condition because right now I'm getting an error => Property 'tag_name' does not exist on type 'string'.ts(2339) – Amos Machora Nov 24 '22 at 09:28
  • You say in the type annotation that you are accepting strings. Then you shouldn't be surprised if you need to deal with strings. I can't tell you how, because I don't know what your code is supposed to do. – Thomas Nov 24 '22 at 09:38