Home > Software engineering >  Type 'CSSStyleDeclaration' does not satisfy the constraint 'string | number | symbol&
Type 'CSSStyleDeclaration' does not satisfy the constraint 'string | number | symbol&

Time:07-03

I created a function for styling the DOM element at once

function css(element: HTMLElement, designs: Record<CSSStyleDeclaration, string>): void {
    for (let design in designs) {
        element.style[design] = designs[design]
    }
}

What I want?

I want to autocomplete the property names as I type. For example

css(someElement, {
  backg...: 'red' // I want all possible css properties that starts with backg like we have in vscode
})

What I am getting!

Type 'CSSStyleDeclaration' does not satisfy the constraint 'string | number | symbol'.

The above error not breaking any thing but it is not auto completing the property name.

CodePudding user response:

I think this is what you need:

function css(element: HTMLElement, designs: Partial<CSSStyleDeclaration>): void {
    for (let design in designs) {
        element.style[design] = designs[design]!
    }
}

CSSStyleDeclaration actually already contains all the properties we need. No need to use a Record here. Since all properties in CSSStyleDeclaration are required, we also need add Partial to make all properties optional.

Now the auto-completion works.

Playground

  • Related