What is the Typescript type for AbortController?

725 Views Asked by At

I can't find any reference about how to define the type for AbortController. I am using it in a React component like so:

    const abortController = useRef();
    
    const doRequest = () => {
            abortController.current = new AbortController();
            window
                .fetch(url, {
                    method: 'GET',
                    signal: abortController.current.signal,
                })
                .then(res => res.json());
        };

const cancelRequest = () => {
  abortController.current.abort();
};
2

There are 2 best solutions below

0
On
const abortController = useRef<AbortController>();

should work

0
On
  type MutableRefObject<T> = {
    current: T | null;  // generic type 
};



  const abortController: MutableRefObject<AbortController> = useRef(null);
    
  const doRequest = () => {
          abortController.current = new AbortController();
          window
              .fetch(url, {
                  method: 'GET',
                  signal: abortController.current.signal,
              })
              .then(res => res.json());
      };

      

const cancelRequest = () => {
        abortController.current?.abort();  // ? for Optional chaining
};

Basically the type of AbortController is AbortController . I created the type MutableRefObject for useRef hook . The RefObject provided by React throws another error because the current property is readonly on RefObject .