javascript - 从 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} />
解决方案
你可以使用CLASS[MEMBER]
它来获取它的类型。
const func: GoogleMap['panTo'] = (latLng) => {
console.log(latLng);
};
推荐阅读
- visual-studio-2019 - 在 Windows 的发布模式下,本征矩阵产品在 ORB-SLAM3 中无法正常工作
- python - Tkinter 按钮:尝试将类方法用于“命令”参数时出现 AttributeError
- javascript - 我收到有关 clearRect 的错误(html 中的画布)
- php - 如何在 PHP 中验证 Google Cloud Services 中的服务帐户?
- javascript - React 函数作为 props 传递显示不是函数?
- javascript - Firebase orderByValue 函数
- node.js - 客户端请求在节点 14.17.2 版本中失败
- c++ - 循环依赖类成员生产者/消费者之间的循环模板参数列表
- python - 无重复的 Pandas 外连接添加新行
- spring-boot - Spring中的STOMP / Websocket架构,客户端和代理之间的解耦