Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set Record in Typescript for string and boolean value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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;

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading