简体   繁体   中英

Typescript function with generic type in useState, allow nullable

I have a hook function like this in React:

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)

How can I define T as nullable?

T = unknown | null T = unknown | null is a default for generic type parameter , it doesn't mean that provided T will allow null . Instead you can specify that null is allowed for state in addition to T :

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];
}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM