Home > Software design >  Why is TypeScript not letting me do a single comparison condition?
Why is TypeScript not letting me do a single comparison condition?

Time:08-15

The error is straightforward: Operator '>' cannot be applied to types 'number' and 'Ref<number>'. But the fact that I cannot make a comparison between 2 numbers is absurd, here's the code, I'm quite new with Typescript, so some help would be very appreciated:

  // Scroll logic:
    let lastScroll = ref<number>(0)

    const handleScroll = () => {
      const body = document.body
      window.addEventListener('scroll', () => {
        const currentScroll = window.scrollY

        if (currentScroll <= 0) {
          body.classList.remove('scroll-up')
        }

        if (
          currentScroll > lastScroll &&
          !body.classList.contains('scroll-down')
        ) {
          body.classList.remove('scroll-up')
          body.classList.add('scroll-down')
        }
        if (
          currentScroll < lastScroll &&
          body.classList.contains('scroll-down')
        ) {
          body.classList.remove('scroll-down')
          body.classList.add('scroll-up')
        }

        lastScroll = currentScroll
      })
    }

the error is in the if() comparison: enter image description here

CodePudding user response:

A ref is not a number. Calling ref returns an object. See here:

Takes an inner value and returns a reactive and mutable ref object, which has a single property .value that points to the inner value.

const count = ref(0)
console.log(count.value) // 0

count.value  
console.log(count.value) // 1

For clarity, rename lastScroll to lastScrollRef. Then change all references of lastScroll to lastScrollRef.value. For example

currentScroll > lastScroll &&

should change to

currentScrollRef.value > lastScroll &&

and so on.

  • Related