2

I have a question around generic type for array input. I have a function called useForm and it accepts the following options

export interface DataType {
  [key: string]: FieldValue;
}

export type FieldValue = boolean | string | string[] | number | {};

export default function useForm<Data extends DataType>(
  { mode, validationSchema, defaultValues, validationFields }: Props<Data> = {
    mode: 'onSubmit',
    defaultValues: {},
  },
): UseFormFunctions<Data> {
}

export interface Props<Data> {
  mode: 'onSubmit' | 'onBlur' | 'onChange';
  defaultValues?: { [key: string]: any };
  validationFields?: string[]; // how do i use generic type here to only allow key from FormData
  validationSchema?: any;
}

type FormData = {
  firstName: string,
  lastName: string,
}

const { register } = useForm<FormData>({
  validationFields: ['test'] // should throw error because it's not firstname or lastname
})

i want it to throw an type error when FormData type is not found.

4
  • could you post the signature of useForm Commented Jun 5, 2019 at 3:40
  • @TitianCernicova-Dragomir sure, thanks for taking a look Commented Jun 5, 2019 at 3:42
  • can you post the code for UseFormFunctions and DataType Commented Jun 5, 2019 at 3:48
  • sure @ShadabFaiz thanks heaps for helping Commented Jun 5, 2019 at 3:54

1 Answer 1

2

You can use keyof to get a union of keys in Data:

export default function useForm<Data extends DataType>(
  { mode, validationSchema, defaultValues, validationFields }: Props<Data> = {
    mode: 'onSubmit',
    defaultValues: {},
  },
): UseFormFunctions<Data> {
  return null!;
}

export interface Props<Data> {
  mode: 'onSubmit' | 'onBlur' | 'onChange';
  defaultValues?: { [key: string]: any };
  validationFields?: Array<keyof Data>; // how do i use generic type here to only allow key from FormData
  validationSchema?: any;
}

type FormData = {
  firstName: string,
  lastName: string,
}

const { register } = useForm<FormData>({
  mode: 'onBlur',
  validationFields: ['test'] // error now
})
Sign up to request clarification or add additional context in comments.

6 Comments

Nice! didn't know you can do that, any chance you can share the reference? would like to learn
@Bruce This is a good start: typescriptlang.org/docs/handbook/…
quick question Array<keyof Data> how to convert into [] version
cause i had an eslint error: 18:22 error Array type using 'Array<T>' is forbidden. Use 'T[]' instead @typescript-eslint/arra , thanks bill
@Bruce (keyof Data)[] but i find this particularly ugly .. for complex types Array<T> is much better ..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.