0

The GoogleMap.d.ts I am using looks like this:

export declare class GoogleMap extends React.PureComponent<GoogleMapProps, GoogleMapState> {
    state: GoogleMapState;
    registeredEvents: google.maps.MapsEventListener[];
    mapRef: Element | null;
    getInstance: () => google.maps.Map<Element> | null;
    panTo: (latLng: google.maps.LatLng | google.maps.LatLngLiteral) => void;
    setMapCallback: () => void;
    componentDidMount(): void;
    componentDidUpdate(prevProps: GoogleMapProps): void;
    componentWillUnmount(): void;
    getRef: (ref: HTMLDivElement | null) => void;
    render(): React.ReactNode;
}

I am using panTo directly and would like to extract its type to use as a function type to avoid code duplication.

// Map Component
const Map = () => {
const [mapObj, setMapObj] = useState(null)
return 
<Map onLoad={(map) => setMapObj(map)}>
<Marker panTo={mapObj?.panTo.bind(mapObj)} />
</Map>
}

// Marker Component
// Bad - this duplicates the panTo type
type PanTo = (latLng: google.maps.LatLng | google.maps.LatLngLiteral) => void;

const Marker = ({panTo}) => <GoogleMarker panTo={panTo} /> 

I have looked into utilities such as Pick but they are going to return a subset of an interface when what I actually want is access a the type of a single method of an interface. Something like this would be ideal:

const Marker = ({panTo}: {panTo: Method<GoogleMap, 'panTo'>}) => <GoogleMarker panTo={panTo} /> 
2

1 Answer 1

0

You can use CLASS[MEMBER] to get its type.

const func: GoogleMap['panTo'] = (latLng) => {
  console.log(latLng);
};
Sign up to request clarification or add additional context in comments.

Comments

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.