Search code examples
reactjstypescriptgenericscomponentsreact-props

How to infer a type from a component prop?


I'd like FormValueType type to be inferred from initialValue prop. Seems to be easy and possible, but I can't figure out how to do that. If you can just turn me towards the right direction it can be also very helpful. I wonder if there's a concept (or some) I miss.

export type AnyObject = {
  // eslint-disable-next-line
  [k: string]: any; 
};


interface FormProps<FormValueType> {
  children?: ReactNode;
  initialValue: FormValueType;
  onChange: (_v: FormValueType) => void;
}
export const BasicForm = ({ children, initialValue }: FormProps<AnyObject>) => {
  const [formState, setFormState] = useState(initialValue);
  return <FormContext.Provider value={{ formState, setFormState }}>{children}</FormContext.Provider>;
};


Solution

  • It looks like you just need to tack on another generic parameter:

    export const BasicForm = <T extends AnyObject>({ children, initialValue }: FormProps<T>) => {
    

    Playground


    Addressing your comment; just add a comma:

    export const BasicForm = <T,>(...) => ...;