TS2322:类型 'string' 不可分配给类型 '"union" | "of" | "strings"'

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

TypeScript 在抱怨

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"'. 

其中对象定义为

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

如果我这样定义它,错误就会消失:

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

但我当然不应该那样做。是我做错了什么还是TS太过分了?

尝试将 as const 添加到 options 定义中:

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

TypeScript 通常会将字符串文字加宽到 string。通过使用 as const,我们可以阻止 TypeScript 扩大文字类型。这将使所有属性 readonly 因此 TypeScript 可以确保值之后不会更改。

您还可以将正确的类型添加到 options:

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

如果您没有显式键入变量,TypeScript 会将其推断为字符串。您可以使用相同的类型输入 options

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

或者简单地说。

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