Search code examples
typescriptformikdestructuringtype-assertionobject-destructuring

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.


Solution

  • 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;