I want to make type inference from a props object given to a component then passed to a render. Object keys are correctly retrieved but all type are typed as unknown.
Need help to understand what’s wrong in my types.
import React, { ReactNode, useEffect } from ‘react’
type RenderPropsType = {
isSubmitted: boolean
}
type ValueOf<T> = T[keyof T]
type PropsType<
O extends object,
K extends keyof O,
V extends ValueOf<O>
> = Record<K, V>
const FormWrapper = <
O extends object,
K extends keyof O,
V extends ValueOf<O>
>({
render,
props,
validationSchema,
}: {
render: (props: PropsType<O, K, V>, formprops: RenderPropsType) => React.ReactNode
// props: Partial<Record<K, (typeof props)[K]>>
props: PropsType<O, K, V>
validationSchema: any
}) => {
const RenderProps = {
isSubmitted: false,
}
return (
<form>
{render?.(props, { ...RenderProps })}
</form>
)
}
type propType = {inactivity: boolean}
const props: propType = { inactivity: false };
<FormWrapper
props={props}
validationSchema={null}
render={(props, formprops) => {
return (
<>{props?.inactivity}</>
)}}></FormWrapper>
>Solution :
You don’t actually need that many generic arguments. In fact, your arguments are used to re-create the initial object, so I can just use one generic argument for the whole props:
const FormWrapper = <
T extends object,
>({
render,
props,
}: {
render: (props: T, formprops: RenderPropsType) => React.ReactNode
props: T
validationSchema: any
}) => {
return null;
}
Testing:
type propType = { inactivity: boolean }
const props: propType = { inactivity: false };
<FormWrapper
props={props}
validationSchema={null}
render={(props, formprops) => { // propType
return (
<>{props?.inactivity}</>
)
}}></FormWrapper>