I have a function that takes an element on the page and adds CSS to its style attribute. I want the argument that is passed to it to be an object with keys such as height
, minWidth
, flexDirection
, etc.
function addStyle (el: HTMLElement, style: Style): void {
for (const property in style) {
el.style[property] = style[property]
}
}
My problem is in typing this object. It's obviously not feasible to define every single CSS property myself. I'm pretty sure that TypeScript should be able to do this itself, I'm just not sure how. This is my best guess:
type Style = Partial<CSSStyleDeclaration>
...but that results in the error "Type 'string | undefined' is not assignable to type 'string'
": TypeScript playground
That specific error can be easily overridden, but I'm wary that it indicates I'm doing something wrong or unintuitive.
Is there a standard way to type an object that contains CSS properties?
style
: developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration – snazzybouche