2

New to Typescript and need some clarification on how to resolve typing errors.

I'm setting the Mapbox container to mapDiv.current--it's giving me this error:

Type 'HTMLDivElement | null' is not assignable to type 'string | HTMLElement'.Type 'null' is not assignable to type 'string | HTMLElement'.ts(2322)

Though this can be fixed by doing mapDiv.current || ''. Is this the right way to resolve this type issue?

export const Map: FunctionComponent = () => {
    const mapDiv = useRef<HTMLDivElement>(null);
    let [map, setMap] = useState(null);

    useEffect(() => {
        const attachMap = (setMap: React.Dispatch<React.SetStateAction<any>>, mapDiv: React.RefObject<HTMLDivElement>) => {
            const map = new mapboxgl.Map({
                container: mapDiv.current, // ERROR
                container: mapDiv.current || '', // NO ERROR
                style: 'mapbox://styles/mapbox/outdoors-v11',
                center: [-121.91390991210938, 40.316184625814095],
                zoom: 10,
            })
            setMap(map);
        }

        !map && attachMap(setMap, mapDiv)

    }, [map])

    return (
        <div className="Map" ref={mapDiv} />
    )

}

1 Answer 1

4

Instead of providing a fallback string value (which might not be the most elegant solution since it is looking for a RefObject), you might want to do a null/undefined check before mounting mapbox in the useEffect hook.

useEffect(() => {
  const attachMap = (setMap: React.Dispatch<React.SetStateAction<any>>, mapDiv: React.RefObject<HTMLDivElement>) => {
    if (!mapDiv.current) {
      return;
    }
    const map = new mapboxgl.Map({
      container: mapDiv.current, // ERROR
      container: mapDiv.current || '', // NO ERROR
      style: 'mapbox://styles/mapbox/outdoors-v11',
      center: [-121.91390991210938, 40.316184625814095],
      zoom: 10,
    })
    setMap(map);
  }

  !map && attachMap(setMap, mapDiv)

}, [map]);
Sign up to request clarification or add additional context in comments.

4 Comments

Huh interesting--so the typescript linter will determine if a null/undefined value has been checked and therefore not throw the error? @wentjun
Yep, that is because of the if (!mapDiv.current) statement that I have added on the attachMap method. It does an early return if the refObject is falsy. Therefore, anything that passes the check will definitely be defined. That's why there is no error.
Anyways, have you tried the above code? And does it work?
Ah I see that's interesting. Yep! It works, thanks for the help, very appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.