Home  >  Q&A  >  body text

TypeScript validation not working properly

I'm having trouble with TypeScript validation.

From my own hook, I get an array (posts) of type Post[] | is not defined.

Then I use Array.prototype.map on that array. TypeScript should give an error like "'posts' is likely 'undefined'" and let me change the code from posts.map to posts?.map.Unfortunately, I don't get the error.

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 don't get the error?

P粉269847997P粉269847997184 days ago279

reply all(1)I'll reply

  • P粉872182023

    P粉8721820232024-03-21 00:52:22

    If we look at the documentation to understand how to use useQuery in TypeScript, we come across amswer.

    useQuery Returns a union type so that if we check whether the response was successful, the language knows that data needs to be defined.

    So when you write

    if (response.error) return;

    TypeScript determines that any code after the condition returns has the data attribute defined.

    reply
    0
  • Cancelreply