I have a TypeScript function with the signature:
function connectRRC<C extends ComponentType<any>>(component: C)
which currently accepts any component.
I'd like to accept ONLY components that have in "props" a given property. E.g. "id: string".
Doing:
function connectRRC<C extends ComponentType<{ id: string }>>(component: C)
doesn't work, cf. this explanation.
ComponentType is defined in React like:
type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;
interface ComponentClass<P = {}, S = ComponentState> extends StaticLifecycle<P, S> {
new (props: P, context?: any): Component<P, S>;
propTypes?: WeakValidationMap<P>;
contextType?: Context<any>;
contextTypes?: ValidationMap<any>;
childContextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
interface FunctionComponent<P = {}> {
(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;
propTypes?: WeakValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
Thanks in advance for any hints!
Update
@sam256 provided a partial working answer, which I found acceptable. However, I found additional use cases that don't work, w/o finding a reasonable explanation. This TS playground link shows them.
This works, as expected:
class GoodComponent2 extends React.Component<{id:string, otherProp:number} & { somethingElse: boolean }> {}
connectRRC(GoodComponent2)
But the following don't work:
class BadComponent3<P = { somethingElse: boolean }> extends React.Component<{id:string, otherProp:number} & P> {}
connectRRC(BadComponent3)
class BadComponent4<P = {}> extends React.Component<{id:string, otherProp:number} & P> {}
connectRRC(BadComponent4)