Use generic ViewModel types in React components
This recipe shows how to keep a generic type (TUser) in your ViewModel and pass it through a React component built with withViewModel.
What you will need:
- A
ViewModelimplementation with generic types (for exampleUserSelectVM<TUser>) withViewModelHOCVMComponentPropstypes
What you will do:
- Add a generic parameter to your view component props
- Use
ViewModelPropsto connect props to a genericViewModel - Cast the resulting component to preserve the generic call signature
tsx
// view.tsx
interface UserSelectUIProps<TUser = any> {
loading?: boolean;
className?: string;
render: (item: TUser) => ReactNode;
}
export const UserSelect = withViewModel<
UserSelectVM,
UserSelectUIProps
>(
UserSelectVM,
({
model,
...uiProps,
}) => {
...
},
) as unknown as <TUser = any>(
props: VMComponentProps<UserSelectVM<TUser>, UserSelectUIProps>,
) => ReactNode;
export type UserSelectProps<TUser = any> = ComponentProps<
typeof UserSelect<TUser>
>;ts
// model.ts
export class UserSelectVM<TUser = any> extends ViewModelBase {
...
}Why the cast is needed:
withViewModelreturns a concreteComponentType, so TypeScript loses the generic call signature.- The explicit
as unknown as <TUser = any>(...) => ReactNoderestores the generic component API for consumers.
