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:

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",
}

Leave a Reply