Home > Software engineering >  Having an Issue with Typescript in VueJS with setProperty
Having an Issue with Typescript in VueJS with setProperty

Time:03-19

Still trying to get my head around typescript so please forgive me but my searches have yielded me no answers. All my other types have worked well but I just can't figure out how to get the value in style.setProperty(propertyName, value) to accept the number.

    function setRotation(vari: HTMLElement , rotationRatio: number) {
      vari.style.setProperty('--rotation', rotationRatio * 360);
    }

Argument of type 'number' is not assignable to parameter of type 'string | null

TypeScript Error--'

CodePudding user response:

A value is expected to be as string.

It can be converted to a string, e.g.:

vari.style.setProperty('--rotation', `${rotationRatio * 360}`);

It's virtually always safe to provide numbers to native functions that expect strings, as they are coerced to strings internally. A type can be also casted, it takes a bit more characters in TS code and a bit less in compiled JS:

vari.style.setProperty('--rotation', (rotationRatio * 360) as unknown as string);
  • Related