I'm trying to investigate why there is a runtime error when I called article.posts[0].title
I have post and posts and I want to call the first post of article (posts[0].title).
typescript assume I have posts size greater than 0 and doesn't throw any error.
type Post = {
title: string
url: string
}
type Posts = Maybe<Array<Post>>
type Article = {
posts: Posts
}
and global type
type Maybe<T> = T | null;
is there a typescript rule, eslint plugin or editor plugin that can detect this issue?
const article: Article = {
posts: [],
}
article.posts?.[0].url
the final and correct code should be
const article: Article = {
posts: [],
}
article.posts?.[0]?.url
thank you in advance.

Try accessing the array at index with
at:Here you can see a playground.
Mind that it won't check the index or the array length, but it will force you to check if the element exists before accessing it.
The above code does not compile:
While the following does compile:
In other words, the type of
arr[0]isstring, while the type ofarr.at(0)isstring | undefined.A good practice could be never accessing an array with the square brackets notation, but:
.at(...)to access specific indices of the array.map,.filter,.reduceand so on to iterate over the array