我在 TypeScript 验证方面遇到问题。
从我自己的钩子中,我得到了一个类型为 Post[] | 的数组(posts)。未定义。
然后我在该数组上使用Array.prototype.map。 TypeScript 应该给出类似 "'posts' is likely 'undefined'" 的错误,并让我将代码从 posts.map 更改为 posts?.map代码>.不幸的是,我没有错误。
我截图来解释我的意思:
usePosts 实现:
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;
我使用 Visual Studio Code,你知道为什么我没有收到错误吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果我们查看文档了解如何为了在 TypeScript 中使用
useQuery,我们遇到了 amswer。useQuery返回一个联合类型,这样如果我们检查响应是否成功,语言就知道需要定义data。因此,当你写作时
TypeScript 确定条件返回后的任何代码都具有已定义的
data属性。