Initialize a generic type object with another generic interface

Viewed 118

I was to provide type safety to a React context.

I have an interface like this

interface Form<T> {
  inputTracker: (val: { name: string; value: T }) => void;
  errorTracker: (val: { name: string }) => boolean;
}

This is the interface for Context. I left it generic so that wherever I use it, I can input custom types for the form.

Now I want to initialize a context with this interface but I am having a hard time.

export const FormContext: Form<T> = createContext<Form<T>>({
  inputTracker: (val) => {},
  errorTracker: (val) => true,
});

I cant seem to find a way to give another generic variable to FormContext type so that I can pass to to Form. I need this type of interface because I want to use this context in many place like this.

const {inputTracker} = useContext<CustomType>(FormContext);

Your help is appreciated.

1 Answers

Not sure I fully understood what you are asking. Is this what you are looking for?

CodeSandbox link

import React from "react";

interface Form<T> {
  inputTracker: (val: { name: string; value: T }) => void;
  errorTracker: (val: { name: string }) => boolean;
}

export const FormContext = React.createContext<Form<number>>({
  inputTracker: (value: { name: string; value: number }) => {},
  errorTracker: (value: { name: string }) => true
});

const App: React.FC = () => {

  const formContext = React.useContext(FormContext);
  const { inputTracker, errorTracker } = formContext;

  return <div>App</div>;
};

export default App;
Related