I have some code using destructuring assignment as follows:
const { values: project, setValues, submitForm } = useFormikContext();
Per the TypeScript type assertion documentation I'd like to use the as keyword to tell the TS compiler that project will always be the type Project.
What's the correct syntax for this? I've tried:
const { values: (project as Project), setValues, submitForm } = useFormikContext();
but that's invalid.
You can use the following syntax to approach this:
const { values: project, setValues, submitForm }: { values: Project; setValues: SomeType1, submitForm: SomeType2} = useFormikContext();
You can create another variable, as well:
const { values: project, setValues, submitForm } = useFormikContext();
const a: Project = project;
By looking at the implementation the definition uses TypeScript Generics
export function useFormikContext<Values>() {
const formik = React.useContext<FormikContextType<Values>>(FormikContext);
return formik;
}
it creates a react context and if you call the hook as:
useFormikContext<Project>()
probably not only the values will be of type Project, but also setValues would accept only object of type Project (unfortunately haven't used the library)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With