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

Can I dynamically gerate a interface from another Interface?

So I am trying to build a custom useForm hook in React. I want to have a function that gives my input all all the Props it needs, which is contained inside the hook, currently it looks like this:

const getInputProps = (name: string) => {
    return {
      name: name,
      //@ts-ignore
      value: values[name],
      //@ts-ignore
      errorMessages: errorMessages[name],
      onChange: onChange,
      setValue: (value: string) => {
        setValues({ ...values, [name]: value });
      },
      showErrorMessages: showErrorMessages,
    };
  };

As you might be able to tell currently I have to suppress the type errors on values[name], because Typescript does not actually know if the name Parameter is a valid key in my Values Object.
My Values Object is declared with a dynamic interface, which is given on method invokation:

export function useForm<InitialState>(
  initialState: InitialState,
  handleSubmit: (e: SyntheticEvent) => void,
  validators: { [key: string]: Validator<any>[] }
) {
  const [values, setValues] = useState<InitialState>(initialState);

now I am left wondering if there is a way for me to generate a type or interface from the keys of the InitialState interface. Example:

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

interface UserFormData {
  value1:string;
  value2:string;
}

will be mapped to

type UserFormDataEnum = "value1" | "value2"

which I can then pass into the getInputProps function:

const getInputProps = (name:UserFormDataEnum) => {...}

>Solution :

You can use the keyof Type Operator as follow:

type UserFormDataEnum = keyof UserFormData
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