Typescript函数参数类型推断问题

wwtsj6pe  于 2023-04-13  发布在  TypeScript
关注(0)|答案(1)|浏览(203)

这里有一段代码:

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类型|number,所以它会抱怨,但它们实际上永远不会是number类型。
如何解决此处的键入检查问题???

agxfikkp

agxfikkp1#

我假设扰乱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
}

相关问题