What's the best way to use a type assertion with destructuring assignment?

953 Views Asked by At

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.

2

There are 2 best solutions below

4
On BEST ANSWER

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;
1
On

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)