Home > database >  Type 'number' is not assignable to type 'string'. ts(2322)
Type 'number' is not assignable to type 'string'. ts(2322)

Time:07-31

So I am trying to create a dragbar for resizing containers.

var handler = document.querySelector('.handler') as HTMLElement;
var wrapper = handler!.closest('.wrapper') as HTMLElement;
var boxA = wrapper!.querySelector('.box') as HTMLElement;
var isHandlerDragging = false;
document.addEventListener('mousedown', function(e) {
  if (e.target === handler) {
    isHandlerDragging = true;
  }
});

document.addEventListener('mousemove', function(e) {
  if (!isHandlerDragging) {
    return false;
  }
  var containerOffsetLeft = wrapper!.offsetLeft;
  var pointerRelativeXpos = e.clientX - containerOffsetLeft;  
  boxA!.style.width = (Math.max(boxAminWidth, pointerRelativeXpos - 8))   'px';
  boxA!.style.flexGrow = 0;   //Type 'number' is not assignable to type 'string'.ts(2322)

How can I declare boxA, so that it is of type number?

I am new to typescript so any suggestions are very much appreciated.

CodePudding user response:

You don't want to change boxA's type. The error it's saying that the property flexGrow of boxA!.style is a string, but you're trying to assign a number to it.

So instead try:

boxA!.style.flexGrow = "0";

Also, you don't really need to use the non-null-assertion operator, the ! operator. Since you've already asserted that boxA is an HTMLElement, Typescript knows that it has a style property.

So, in the end you can write it like this:

boxA.style.flexGrow = "0";
  • Related