Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 348
mikemaccana Avatar asked Nov 01 '25 20:11

mikemaccana


2 Answers

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;
like image 186
Roman A. Avatar answered Nov 03 '25 12:11

Roman A.


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)

like image 43
Teneff Avatar answered Nov 03 '25 10:11

Teneff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!