What is the Typescript type for AbortController?

712 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 answers

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

should work

0
Josef Abo Shady 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 .