Home > Mobile >  typescript types definition with react difficulties
typescript types definition with react difficulties

Time:07-05

I am trying to convert some of my old javascript code to typescript and I know I need to have all my types defined but here I have been having trouble because even if I define them I get an error.

This error is without the types defined on mapRef and current which are the two things that typescript is shouting me about.

Object is possibly 'undefined'.

This is the code without type definitions

const mapRef = React.useRef();
  const onMapLoad = React.useCallback((map) => {
    mapRef.current = map;
  }, []);
  
  const panTo = React.useCallback(({ lat, lng }) => {
    mapRef.current.panTo({ lat, lng }); // This line is shouting the error
    mapRef.current.setZoom(14); // This line is shouting the error
  }, []);

The way I have tried to define the types is as follows:

A) mapRef<Number>.current<Number>.panTo({ lat, lng });
B) mapRef<Any>.current<Any>.setZoom(14);
C) mapRef?.current?.panTo({ lat, lng });

But all of this presents new problems and errors... These are the error that I am getting if I do any of these

A) 'mapRef' refers to a value, but is being used as a type here. Did you mean 'typeof mapRef'?

B) Type 'MutableRefObject' has no signatures for which the type argument list is applicable.

C) Property 'panTo' does not exist on type 'never'.

Any help or any post, or documentation links are appreciated

CodePudding user response:

You will need to explicitly tell TypeScript what you're going to box into the ref. I also explicitly default it to null here; you could use undefined too.

Assuming map is of type MyMap,

const mapRef = React.useRef<MyMap | null>(null);
const onMapLoad = React.useCallback((map) => {
  mapRef.current = map;
}, []);
  
const panTo = React.useCallback(({ lat, lng }) => {
  const map = mapRef.current;
  if(!map) return;  // No map (yet)? (This return narrows the type of `map` from `MyMap | null` to just `MyMap`, so the following work.)
  map.panTo({ lat, lng });
  map.setZoom(14);
}, []);

should be enough.

You may also need to annotate the onMapLoad callback's parameter (to e.g. MyMap or MyMap | null).

  • Related