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.
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)
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.