Home > Blockchain >  Why is the element of array (string[] ) inferred as undefined?
Why is the element of array (string[] ) inferred as undefined?

Time:06-22

Here is function called checkMultipleImgs returning array filed with string. (string[])

  const checkMultipleImgs = async (fileName: string): Promise<string[]> => {
    const { data, error } = await supabase.storage.from('fitting').list('', {
      offset: 0,
      sortBy: { column: 'name', order: 'asc' },
      search: fileName,
    });

    return data ? data.map((item) => item.name) : [];
  };

And there's this variable "newUrls" which is the return value of checkMultipleImgs function (string[])

      const newUrls = await checkMultipleImgs(fileName);
      if (newUrls && newUrls.length > 0) {
        for (let i = 0; i < newUrls.length; i  ) {
          const newFileName = newUrls[i];
          const url = await getImgUrl(newFileName);
          if (url) {
            urls.push(url);
          }
        }
      }

But.. why do I get this error?

It's saying newUrls[i] can be string | undefined. I don't know why undefined is inferred here.

enter image description here

CodePudding user response:

Since you are taking newUrls array from a promise, it also has a possiblity to get rejected and the value can also be undefined. So, with the same reason typescript infers that you newUrls[i] variable can also have an undefined value.

Solution for this is to apply a type for the value while assignment.

const newFileName = newUrls[i] as string;

This should solve the type-error you're getting.

CodePudding user response:

I assume it's 'noUncheckedIndexedAccess' in TS, which adds 'undefined' as a return type for arrays.

const myFunc = (s: string) => console.log(s);
const myArr = ['test', 'array'];

myFunc(myArr[0]) // <-- the warning

Potentially solve with forEach, avoiding the index lookup

const myFunc = (s: string) => console.log(s);
const myArr = ['test', 'array'];

myArr.forEach(myFunc)

// or 

myArr.forEach((myVal) => {
  // do things with the string
})

or assert that it's not undefined.

  • Related