gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:27:30 27 4
gpt4 key购买 nike

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 在这里过于咄咄逼人?

enter image description here

最佳答案

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

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

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

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

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

关于typescript - TS2322 : Type 'string' is not assignable to type '"union"| "of" | "strings"',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72340281/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com