【发布时间】:2021-04-05 12:37:45
【问题描述】:
我知道这是一个 100% 的菜鸟问题,但我无法处理自己并想知道答案。
type SweetAlertPosition =
'top' | 'top-start' | 'top-end' | 'top-left' | 'top-right' |
'center' | 'center-start' | 'center-end' | 'center-left' | 'center-right' |
'bottom' | 'bottom-start' | 'bottom-end' | 'bottom-left' | 'bottom-right';
主界面(简体):
interface SweetAlertOptions {
...,
position?: SweetAlertPosition
}
class Swal {
mixin(options: SweetAlertOptions)
}
现在,如果我明确地将选项传递给 .mixin 调用:Swal.mixin({ position: 'bottom' }) - 没有错误。 但是如果我在某个 const 对象中预定义选项:
defaultOptions = {
position: 'bottom'
}
现在传递会出错 - Swal.mixin(defauiltOptions)
Types of property 'position' are incompatible.
Type 'string' is not assignable to type '"top" | "top-start" | "top-end" | "top-left" | "top-right" | "center" | "center-start" | "center-end" | "center-left" | "center-right" | "bottom" | "bottom-start" | "bottom-end" | "bottom-left" | "bottom-right" | undefined'.
我已经发现必须将 String 类型转换为 const:
defaultOptions = {
position: 'botton' as const | as SweetAlertPosition
}
但是为什么通过 const obj(defaultOptions) 传递选项会使 position 属性变成 String 类型,而直接传递却不是 oO 呢?
【问题讨论】:
标签: typescript