Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript type inference – Object key seen as unknown

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>

Here is a playground

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>

playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading