[英]Typescript function with generic type in useState, allow nullable
I have a hook function like this in React:我在 React 中有一个像这样的钩子 function:
export function useFetch<T = unknown|null>(url: string) : [T, boolean] {
const accessToken = useAccessToken();
const [data, setData] = useState<T>(null); // TS ERROR
const [isLoading, setIsLoading] = useState<boolean>(true);
useEffect(() => {
if (accessToken) {
fetch(`/api/v1${url}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
.then((res) => res.json())
.then(data => {
setData(data);
setIsLoading(false);
});
}
}, [accessToken, url]);
return [data, isLoading];
}
But I get this error: Argument of type 'null' is not assignable to parameter of type 'T | (() => T)'.ts(2345)
但我收到此错误:
Argument of type 'null' is not assignable to parameter of type 'T | (() => T)'.ts(2345)
Argument of type 'null' is not assignable to parameter of type 'T | (() => T)'.ts(2345)
How can I define T as nullable?如何将 T 定义为可为空的?
T = unknown | null
T = unknown | null
is a default for generic type parameter , it doesn't mean that provided T
will allow null
. T = unknown | null
是泛型类型参数的默认值,但这并不意味着提供的T
将允许null
。 Instead you can specify that null
is allowed for state in addition to T
:相反,您可以指定
null
除了T
之外还允许 state :
export function useFetch<T>(url: string): [T | null, boolean] {
const accessToken = useAccessToken();
const [data, setData] = useState<T | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
// ...
return [data, isLoading];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.