import React, { ComponentType, FunctionComponent } from "react"; import { Call, Fn, KeepNeversFn, PickFn } from "../types/Fn"; import { Hoc } from "../types/Hoc"; import { newHoc } from "../utils/newHoc"; interface WithPickFn extends Fn { return: Call< KeepNeversFn>, { [K in Extract[0]]: [ K, K extends PickNames ? Extract[1] : undefined extends Extract[1] ? Extract[1] : never, ]; }[Extract[0]] >; } type WithPickHoc = ( pickNames: PickNames[], ) => Hoc<[WithPickFn]>; /** * Pick, which is actually ignore other props * * @see {@link withOmit} * @example * const user = { * username: "Some username", * password: "s0m3 p4ssw0rd", * vitalSecretInfo: "..." * }; * function RevealInfo( * { username, password, vitalSecretInfo }: * { username: string; password?: string; vitalSecretInfo: string } * ) { * ... * } * const SafeRevealInfo = withPick(["username"])(RevealInfo); * * // is equivalent to * // password and vitalSecretInfo is not included */ export const withPick = newHoc(function withPick( Component: ComponentType, pickNames: string[], ): FunctionComponent { const pickSet = new Set(pickNames); return function WithPick(props: any): JSX.Element { const newProps = { ...props }; for (const key in newProps) { if (!pickSet.has(key) && key in newProps) { delete newProps[key]; } } return ; }; });