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

TS2322: Type 'string' is not assignable to type '"union" | "of" | "strings"'

TypeScript is complaining

TS2322: Type '{ clientSecret: string; loader: string; }' is not assignable to type 'StripeElementsOptions'.   
  Types of property 'loader' are incompatible.     
    Type 'string' is not assignable to type '"always" | "auto" | "never"'. 

Where the object is defined as

const options = {
    clientSecret: paymentIntent.clientSecret,
    loader: "always",
}

The error goes away if I define it like this instead:

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

const options = {
    clientSecret: paymentIntent.clientSecret,
    loader: "always" as "always",
}

But surely I shouldn’t have to do that. Am I doing something wrong or is TS being overly aggressive here?

enter image description here

>Solution :

Try to add as const to the options definiton:

const options = {
    clientSecret: paymentIntent.clientSecret,
    loader: "always",
} as const

TypeScript will often widen string literals to string. By using as const, we can stop TypeScript from widening literal types. This will make all properties readonly so TypeScript can make sure the values won’t change afterwards.

You could also add the correct type to options:

const options: StripeElementsOptions = {
    clientSecret: paymentIntent.clientSecret,
    loader: "always",
}
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