How do I declare a type for only an object’s writable properties?

  Kiến thức lập trình

Here is a very simplified version of the code that I am working on, that aims to create 2 new divs in the X and Y midpoints of the parent div. Ignore that there are far more optimal ways to do this – this is only a snippet of the logic for example purposes.

I’m aiming to save repeat code by iterating over the main logic twice, swapping out ‘width’ and ‘left’ for ‘height’ and ‘top’ on the second pass through.

type WritableCSSProperties = Omit<CSSStyleDeclaration, 'parentRule' | 'length' | 'item' |
  'getPropertyPriority' | 'getPropertyValue' | 'removeProperty' | 'setProperty'>;

const parentDiv = document.querySelector('#parentDiv')!;
const clientRect = parentDiv.getBoundingClientRect();

const clientRectProperties: ReadonlyArray<keyof DOMRect> = ['width', 'height'];
const styleProperties: ReadonlyArray<string & keyof WritableCSSProperties> = ['left', 'top'];

for (let a = 0; a < 2; a++) {
  let midpoint = (clientRect[clientRectProperties[a]] as number) / 2
  const newDiv = document.createElement('div');
  (newDiv.style as WritableCSSProperties)[styleProperties[a]] = `${midpoint}px`;
  parentDiv.appendChild(newDiv);
}

I have come up with the above solution, creating the WritableCSSProperties type to prevent TypeScript from being upset by read-only properties being present in the CSSStyleDeclaration object.

Is there not a more elegant solution for omitting read-only properties from an object when type casting? This seems like something that would not be uncommon, and I feel like my implementation here is not necessarily optimal.

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT