Use of ''instance of' in union types. ts(2358). Left side of instance of must be 'any', object or a type parameter

Viewed 314

Following this question, have this code: (See line with comment //ERROR: ts(2358))

const w = ((mat: Float32Array | Vec4) => { 
    if (mat instanceof Float32Array) {
      const sizeIsOk = mat.length == 4;
      if (sizeIsOk) {
        return <number>mat[4];
      } else {
        console.log('point does not have 4 coordinates. 4th default is 1 if not defined');
        return mat.length > 4 ? mat[3] : 1;
      }
    } else if (mat instanceof Vec4) { //ERROR: ts(2358)

    }
    return 0;
  })(matrix);

I would be OK if the left hand side has to be 'any', an object type (or class instance I believe) or a type parameter type always, buy not only in the else clause.

This is solved adding the 'any' type in the lambda. It is not working if added in the function argument type union which I also find surprising, as the any type must me added in the lambda argument where the argument passed in the function has its union type defined already.

Solution code just adding any type in the lamda:

function foo(matrix: Float32Array | Vec4) { // Any in the union here does not work!
  const w = ((mat: Float32Array | Vec4 | any) => { 
    if (mat instanceof Float32Array) {
      const sizeIsOk = mat.length == 4;
      if (sizeIsOk) {
        return <number>mat[4];
      } else {
        console.log('point does not have 4 coordinates. 4th default is 1 if not defined');
        return mat.length > 4 ? mat[3] : 1;
      }
    } else if (mat instanceof Vec4) {

    }
    return 0;
  })(matrix);
}

I believe this has to do with how typescript handles the type check with instance of, but can't get to understand if this is the designed and normal behaviour and why.

So to sum up, why instanceof does not compile in the else clause, and any type must me added in the lambda argument where the argument passed in is already define in its respective type?

side notes: 1.- Copy pasting the code in the editor might be faster to see my point instead of digging through the lecture of the explained problem, as its quite immediate, but long to explain in words correctly. 2.-in case of being curious or want to dig in this interesting topic find some resources I had a look to, which did not leave me with the satisfation of getting to the end of the issue. Resouces one and two

0 Answers
Related