solidjs-community / solid-primitives

A library of high-quality primitives that extend SolidJS reactivity.
https://primitives.solidjs.community
MIT License
1.18k stars 114 forks source link

Resize-observer ResizeHandler element support generics #647

Closed Phinome closed 8 hours ago

Phinome commented 2 weeks ago

Describe The Problem To Be Solved

in case:

let ref
createResizeObserver(() => ref, ({ width, height }, el) => {
  if (el === ref) console.log(width, height)
});
<div ref={ref}/>

el is HTMLElement, but handler of parameter el to Element.

i want to get offsetWidth or offsetHeight from el, but typescript would checked failed: "The Element type has no offsetWidth or offsetHeight attribute."

Suggest A Solution

just like this:

export type ResizeHandler<T> = (
  rect: DOMRectReadOnly,
  element: T,
  entry: ResizeObserverEntry,
) => void;
Phinome commented 3 days ago

no body care?

maciek50322 commented 2 days ago

In typescript you can always force different type if you are sure it is different type or check it

let ref;
createResizeObserver(() => ref, ({ width, height }, el) => {
  // if you are sure of the type
  (el as HTMLElement).offsetWidth;
  // checking if it contains prop you want
  if (offsetWidth in el) el.offsetWidth;
});
<div ref={ref}/>

Generics will simplify this for you, but note that typescript also generalize types whenever it can, so if we had generics and

let ref: HTMLElement;
let ref2: Element;
createResizeObserver(() => [ref, ref2], ({ width, height }, el) => {
  // `el` would be generalized here to type `Element`, because `HTMLElement` extends `Element`
  // still would have to check it manually
});
<div ref={ref}/>