How To Check If Array Is Empty In TypeScript

When processing JSON responses in TypeScript, how do you safely check if a variable is an array and is not empty?

Let’s say we get a response from an API (in this example, it’s Kontent API):

const blogPosts: BlogPost[] = (await deliveryClient
.it…


This content originally appeared on DEV Community and was authored by Ondrej Polesny

When processing JSON responses in TypeScript, how do you safely check if a variable is an array and is not empty?

Let's say we get a response from an API (in this example, it's Kontent API):

const blogPosts: BlogPost[] = (await deliveryClient
  .items<BlogPost>()
  .type("blog_post")
  .toPromise())?.data?.items

We expect that response to be an array of BlogPost objects. Also, note the ?. notation that allows us to unwind the response and select just the data we need. If the response doesn't have the expected format, we will get null instead of undefined error.

Therefore, we first need to check if the response is a defined array:

if (!Array.isArray(blogPosts)) {
  throw new Error("Response has a wrong format")
}

The Array.isArray function will catch all possible values:

// all these calls return false
Array.isArray(undefined)
Array.isArray(null)
Array.isArray({})

// DON'T DO THIS
// as there is no need for checking the variable separately
if (blogPosts && Array.isArray(blogPosts)) { }

// DO THIS
// Array.isArray() is doing the null and
// undefined check automatically
if (Array.isArray(blogPosts)){ }

Note: Check MDN Web Docs for more information.

Then, we check if the array contains any items via .length property:

if (blogPosts.length == 0) {
  throw new Error("Response contains no items")
}

And that's it. 💪

The full code looks like this:

const blogPosts: BlogPost[] = (await deliveryClient
  .items<BlogPost>()
  .type("blog_post")
  .toPromise())?.data?.items

if (!Array.isArray(blogPosts) || blogPosts.length == 0){
  throw new Error("No data")
}

// all good here
console.log(blogPosts)

You can also wrap the code in try/catch block to make sure you also catch errors from network communication.

If you need any help with processing your Kontent data, join our Discord! 😎


This content originally appeared on DEV Community and was authored by Ondrej Polesny


Print Share Comment Cite Upload Translate Updates
APA

Ondrej Polesny | Sciencx (2021-12-08T09:12:06+00:00) How To Check If Array Is Empty In TypeScript. Retrieved from https://www.scien.cx/2021/12/08/how-to-check-if-array-is-empty-in-typescript/

MLA
" » How To Check If Array Is Empty In TypeScript." Ondrej Polesny | Sciencx - Wednesday December 8, 2021, https://www.scien.cx/2021/12/08/how-to-check-if-array-is-empty-in-typescript/
HARVARD
Ondrej Polesny | Sciencx Wednesday December 8, 2021 » How To Check If Array Is Empty In TypeScript., viewed ,<https://www.scien.cx/2021/12/08/how-to-check-if-array-is-empty-in-typescript/>
VANCOUVER
Ondrej Polesny | Sciencx - » How To Check If Array Is Empty In TypeScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/12/08/how-to-check-if-array-is-empty-in-typescript/
CHICAGO
" » How To Check If Array Is Empty In TypeScript." Ondrej Polesny | Sciencx - Accessed . https://www.scien.cx/2021/12/08/how-to-check-if-array-is-empty-in-typescript/
IEEE
" » How To Check If Array Is Empty In TypeScript." Ondrej Polesny | Sciencx [Online]. Available: https://www.scien.cx/2021/12/08/how-to-check-if-array-is-empty-in-typescript/. [Accessed: ]
rf:citation
» How To Check If Array Is Empty In TypeScript | Ondrej Polesny | Sciencx | https://www.scien.cx/2021/12/08/how-to-check-if-array-is-empty-in-typescript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.