One of the functions I am working with is useFormState()
, which requires an object initialValues
of type FormType
as a parameter.
type FormType = {
email: string;
password: string;
rememberMe: boolean;
}
...
const initialValues: FormType = {
email: '',
password: '',
rememberMe: false,
}
const { values, touched, errors, updateField } = useFormState<FormType, keyof FormType>(initialValues);
The function useFormState()
is expected to return an object with keys from the FormType
:
touched: {
email: true,
password: false,
rememberMe: false
}
To achieve this typing, I need to extract the "keys" type internally by passing it as the second generic type keyof FormType
.
This leads to my question - Is there a way to only pass the type FormType
and internally extract the keys type?
The function is defined as follows:
const useFormer = <T, K extends keyof T>(props) => {
...
}
Although I could let TypeScript infer the types by omitting them, it becomes confusing when additional properties are added using T
.
- TS can misinterpret the types, and I want users of the function to be certain that what they pass matches the specified Type, hence preferring a single generic type.
It seems like the second type argument K extends keyof T
could be completely inferred, but TypeScript requires it if only one type argument is passed.
Is there a way to work around this and use just one type argument?