Home > Software design >  TS2322: Type 'string' is not assignable to type '"union" | "of" |
TS2322: Type 'string' is not assignable to type '"union" | "of" |

Time:05-23

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

CodePudding user response:

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

CodePudding user response:

If you don't explicitly type the variable, TypeScript will infer it as a string. You could type your options with the same type.

const options: { clientSecret: string; loader: "always" | "auto" | "never"; } = {
  clientSecret: paymentIntent.clientSecret,
  loader: "always",
}

Or simply.

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