PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] Why is TypeScript not letting me do a single comparison condition?

 October 15, 2022     dom, frontend, javascript, typescript, vue.js     No comments   

Issue

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


Solution

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.



Answered By - CertainPerformance
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing