Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript validation doesn't work properly

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I took a screenshot to explain what I mean:
enter image description here

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading