首页 > 解决方案 > 从 Typescript 的接口中提取方法类型

问题描述

GoogleMap.d.ts我正在使用的看起来像这样:

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;
}

panTo直接使用并想提取其类型以用作函数类型以避免代码重复。

// 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} /> 

我已经研究了诸如此类的实用程序,Pick但是当我真正想要的是访问接口的单个​​方法的类型时,它们将返回接口的子集。像这样的东西是理想的:

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

标签: javascriptreactjstypescript

解决方案


你可以使用CLASS[MEMBER]它来获取它的类型。

const func: GoogleMap['panTo'] = (latLng) => {
  console.log(latLng);
};

推荐阅读