我正在try 调查为什么当我调用文章.post[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
}
和全局类型
type Maybe<T> = T | null;
有没有打字规则、eslint插件或编辑器插件可以检测到这个问题?
const article: Article = {
posts: [],
}
article.posts?.[0].url
最终且正确的代码应该是
const article: Article = {
posts: [],
}
article.posts?.[0]?.url
提前谢谢你.