TypeScript validation not working properly
P粉269847997
P粉269847997 2024-03-20 09:14:31
0
1
355

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粉269847997
P粉269847997

reply all(1)
P粉872182023

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template