Skip to content

Improvement to return type of useMouse #237

@pc-erin

Description

@pc-erin

I noticed that the return type of useMouse isn't exactly reflective of the data returned.

If we made it shaped more like this:

export type MousePosition = MousePositionOver | MousePositionOut

type MousePositionOver = {
  x: number
  y: number
  pageX: number
  pageY: number
  clientX: number
  clientY: number
  screenX: number
  screenY: number
  elementWidth: number
  elementHeight: number
  isOver: true
  isDown: boolean
  isTouch: boolean
}

type MousePositionOut = {
  x: undefined
  y: undefined
  pageX: undefined
  pageY: undefined
  clientX: undefined
  clientY: undefined
  screenX: undefined
  screenY: undefined
  elementWidth: undefined
  elementHeight: undefined
  isOver: false
  isDown: false
  isTouch: boolean
}

This preserve additional type information since, if you check that mouseData.isOver is true, the inside of that conditional will see all the values as numbers and not have to check each property individually.

Also, if we switch from null to undefined for the missing values, you can use default values during destructuring:

const { x = 0, y = 0, isOver } = useMouse(ref)

The change from null to undefined would be breaking, so if you prefer we could put off merging that until a planned major version bump, but the rest should be safe.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions