Home > Mobile >  Can I dynamically gerate a interface from another Interface?
Can I dynamically gerate a interface from another Interface?

Time:04-26

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:

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) => {...}

CodePudding user response:

You can use the keyof Type Operator as follow:

type UserFormDataEnum = keyof UserFormData
  • Related