I have a problem with TypeScript validation.
From my own hook I get an array (posts) that has the type of Post[] | undefined.
I then use Array.prototype.map on that array. TypeScript should give an error like "'posts' is probably 'undefined'" and make me change my code from posts.map to posts?.map. Unfortunately, I have no errors.
I took a screenshot to explain what I mean:

usePosts implementation:
import axios from "axios";
import { useQuery } from "@tanstack/react-query";
interface Post {
id: number;
title: string;
body: string;
userId: number;
}
const usePosts = () => {
const fetchPosts = () =>
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.data);
return useQuery<Post[], Error>({
queryKey: ["posts"],
queryFn: fetchPosts,
staleTime: 10 * 1000
});
}
export default usePosts;
I use Visual Studio Code, do you know why I get no errors?
>Solution :
If we check out the the documentation for how to work with useQuery in TypeScript, we come across the amswer.
useQuery returns a union type such that if we check the response for success the language knows that data is necessary defined.
Thus when you write
if (response.error) return;
TypeScript determins that any code after the conditional return has a defined data property.