Home > database >  Type of a prop based on type of other props
Type of a prop based on type of other props

Time:11-24

I have a general component that accepts a prop named component and the rest of the props should be the props of that specific component. how can I do it in typescript?

i.e. :

 <FormField component={Input} ... />

This FormField should accept whatever props Input component accepts.

Note:

  • I want to infer the type from props. don't want to pass additional type

CodePudding user response:

I think you can do this using a generic

const FormField = <K,>(props: FormFieldProps & K) => {
    //Your component here
}

Usage :

<FormField<InputProps> .... />

CodePudding user response:

Starting from @A.Vinuela's answer, i just make it more easy to use, without the need to know the component's props interface, using also the React build-in helpers.


I think you can do this using a generic and the React.ComponentPropsWithoutRef<T> build-in helper (or the React.ComponentPropsWithRef<T>, depending on your needs).

const FormField = <K>(props: FormFieldProps & React.ComponentPropsWithoutRef<K>) => {
    //Your component here
}

Usage :

<FormField<typeof AnyComponent> .... />

Unfortunately it is not possible to determine the type of a property depending on the dynamic type of another property (at least, that I know of).

What you would need is:

// UNFORTUNATELY THIS IS NOT VALID
interface FormFieldProps {
component: T,
props: React.ComponentPropsWithoutRef<T>
}

But you can't use a dynamic type variable such as T as the type of the component prop.

So i think that the best solution is using the generic as shown above.

  • Related