R1ZEN / react-yandex-maps

Yandex.Maps API bindings for React (fork https://github.com/gribnoysup/react-yandex-maps)
https://pbe-react-yandex-maps.vercel.app
MIT License
120 stars 19 forks source link

Как правильно использовать с typescript #41

Closed YasKur closed 1 year ago

YasKur commented 1 year ago

Откуда нужно добавлять типы для корректной работы ts.

Пример:

const [currentMap, setCurrentMap] = useState<YMapsApi | null>(null);

useEffect(() => {
    // ESLint: Unsafe member access .getBounds on an `any` value.(@typescript-eslint/no-unsafe-member-access)
    if (!currentMap?.geoObjects.getBounds()) {
      return;
    }
    // ESLint: Unsafe member access .getBounds on an `any` value.
    currentMap.setBounds(currentMap.geoObjects.getBounds(), { zoomMargin: 20 });
  }, [currentMap]);

Если посмотреть в типы:

interface AnyObject {
  [key: string]: any;
}

export interface YMapsApi extends AnyObject {}

Такая же проблема будет если будем делать что-то делать с элементами управления:

<SearchControl
              instanceRef={(ref) => {
                setSearchControl(ref);
              }}
>
// ESLint: Unsafe member access .getResultsArray on an `any` value.
const results = searchControl.getResultsArray();

Можно как-то подружить с - https://www.npmjs.com/package/@types/yandex-maps? Или есть какие-то другие решения?

R1ZEN commented 1 year ago

@YasKur библиотека уже имеет зависимость на @types/yandex-maps, чтобы протипизировать ref в вашем случае, можно сделать так:

import { useState } from "react";
import { YMaps, Map, SearchControl } from "@pbe/react-yandex-maps";
import ymaps from "yandex-maps";

export default function App() {
  const [, setSearchControl] = useState<
    ymaps.control.SearchControl | undefined
  >();

  const defaultState = {
    center: [55.751574, 37.573856],
    zoom: 5
  };

  return (
    <YMaps>
      <Map defaultState={defaultState}>
        <SearchControl
          instanceRef={(ref: ymaps.control.SearchControl) => {
            setSearchControl(ref);
          }}
        />
      </Map>
    </YMaps>
  );
}

https://codesandbox.io/s/intelligent-sound-0s4lpv?file=/src/App.tsx

Хорошо бы это конечно инкапсулировать внутрь библиотеки))