all.
I have a Formik field in React and need to set the values of the fields to a string or a boolean
const handleSubmit = async (values: Record<string, string>) => {
const checkoutDetails = await getCheckout({ checkoutId: checkoutId });
if (checkoutDetails.errors) {
setSubmitError(true);
return;
}
const email = checkoutDetails.data.checkoutById.customer?.email;
const customer = await addCustomer({
firstName: values.firstName,
lastName: values.lastName,
checkoutId: checkoutId as string,
customerId: null,
email: email,
ochId: null,
emailMarketingConsent: values.emailMarketing as unknown as boolean,
smsMarketingConsent: values.smsMarketing as unknown as boolean,
});
With the above code I have to cast the last two values as they are boolean values, I have tried a few ways including writing custom types but it seems to error one way or the other
Do not get me wrong, it does work like this, but I feel there is a better way without typecasting to unknown as boolean.
Can anyone show me how to set the Record type so I do not need to cast it?
Thank you!
CodePudding user response:
Record<string, string| boolean>
could be a way but you'll still need the type assertion.
or you could do an intersection :
type Foo = Record<string, string> & {emailMarketing: boolean, smsMarketing: boolean}
declare const foo:Foo;
foo.firstName // string
foo.emailMarketing // boolean;
foo.smsMarketing // boolean;