我这里有这段代码:
export default function (triggerEl: Ref<HTMLDivElement>, contentEl: Ref<HTMLDivElement>, placement: Ref<Placement> | Placement = 'auto', offset: Ref<number> | number = 0) {
placement = ref(placement) as Ref<Placement>
offset = ref(offset)
const { top: triggerTop, right: triggerRight, bottom: triggerBottom, left: triggerLeft, width: triggerWidth, height: triggerHeight } = useElementBounding(triggerEl)
const { top: contentTop, right: contentRight, bottom: contentBottom, left: contentLeft, width: contentWidth, height: contentHeight } = useElementBounding(contentEl)
const position = computed<PopperPosition>(() => {
let top = Number.MIN_SAFE_INTEGER
let left = Number.MIN_SAFE_INTEGER
if (placement.value === 'top') {
top = triggerTop.value - contentHeight.value - offset.value
left = triggerLeft.value + triggerWidth.value / 2 - contentWidth.value / 2
}
return {
top,
left,
}
})
return null
}
我已经将'placement'和'offset'参数转换为它们对应的'Ref'类型,但下面的代码仍然认为它们是类型 Ref |数字,所以它抱怨,但他们实际上永远不会是数字类型。
我如何解决这里的打字检查问题???
我想弄乱 TS 推理的来源位于第 21 和 22 行(重新分配变量值):
placement = ref(placement) as Ref<Placement>
offset = ref(offset)
我建议改为创建新变量,因此最终代码将如下所示:
export default function (triggerEl: Ref<HTMLDivElement>, contentEl: Ref<HTMLDivElement>, placement: Ref<Placement> | Placement = 'auto', offset: Ref<number> | number = 0) {
const placementRef = ref(placement)
const offsetRef = ref(offset)
const { top: triggerTop, right: triggerRight, bottom: triggerBottom, left: triggerLeft, width: triggerWidth, height: triggerHeight } = useElementBounding(triggerEl)
const { top: contentTop, right: contentRight, bottom: contentBottom, left: contentLeft, width: contentWidth, height: contentHeight } = useElementBounding(contentEl)
const position = computed<PopperPosition>(() => {
let top = Number.MIN_SAFE_INTEGER
let left = Number.MIN_SAFE_INTEGER
if (placementRef.value === 'top') {
top = triggerTop.value - contentHeight.value - offsetRef.value
left = triggerLeft.value + triggerWidth.value / 2 - contentWidth.value / 2
}
return {
top,
left,
}
})
return null
}