React Query queryKey的TypeScript类型及useQuery调用报错问题
React Query + TypeScript:validateToken函数参数类型解决方案
报错原因
你之前指定的QueryFunction<boolean, [string, string | null | undefined]>存在类型不兼容问题:React Query的QueryKey本质是只读数组类型,而你定义的[string, string | null | undefined]是可变数组,导致类型无法匹配,触发TypeScript报错。
正确类型写法
有三种等价的正确写法,任选其一即可:
写法1:直接指定只读数组类型的QueryFunction
import { QueryFunction } from '@tanstack/react-query'; export const validateToken = async ({ queryKey }: QueryFunction<boolean, readonly [string, string | null | undefined]>) => { console.log('validating token'); const [_, token] = queryKey; if (token) { const res = await axios.get<boolean>(BACKEND_URL + '/', { headers: { Authorization: token, }, }); return res.data; } else { return false; } };
写法2:使用QueryFunctionContext类型
import { QueryFunctionContext } from '@tanstack/react-query'; export const validateToken = async ({ queryKey }: QueryFunctionContext<readonly [string, string | null | undefined]>) => { // 函数内容同上 };
写法3:单独定义queryKey类型(更清晰)
import { QueryFunction } from '@tanstack/react-query'; // 单独定义查询键的只读类型 type ValidateTokenQueryKey = readonly ['isTokenValid', string | null | undefined]; export const validateToken = async ({ queryKey }: QueryFunction<boolean, ValidateTokenQueryKey>) => { // 函数内容同上 };
为什么这样可行
React Query的查询函数参数(QueryFunctionContext)中的queryKey默认是只读数组类型,将你的queryKey类型声明为readonly后,就能和QueryKey的底层定义对齐,解决“只读类型无法赋值给可变类型”的报错。同时,useIsTokenValid中传入的['isTokenValid', token]会被TypeScript自动推导为只读数组,和validateToken的类型参数完全匹配,useQuery调用处的报错也会消失。
内容的提问来源于stack exchange,提问作者Leonardo Trapani
相关产品推荐
相关产品推荐

