TS: Vector3 interface not descriptive enough to support this valid usage

Description of the problem

The following code works, but TypeScript does not compile with the present Vector3.d.ts

  // vector between center of head and center of ear
  const earVector = new THREE.Vector3(1.44, 0.6, -0.3);

  const leftEar = new THREE.SphereGeometry(1, 32, 32).applyMatrix4(new THREE.Matrix4().makeScale(0.4, 0.4, 0.25));
  const rightEar = leftEar.clone();

  leftEar.translate(...earVector.toArray());
  earVector.x = -earVector.x;
  rightEar.translate(...earVector.toArray());

BUG (compile error):
Expected 3 arguments, but got 0 or more. ts(2556)

EXPECTED:
Given that the code behaves as expected, I would expect it to compile.
(I would also expect the aesthetics of this use of the spread operator to divide opinion)

Three.js version
  • Dev
  • r116
Browser
  • All of them
  • Chrome
  • Firefox
  • Internet Explorer
OS
  • All of them
  • Windows
  • macOS
  • Linux
  • Android
  • iOS
Hardware Requirements (graphics card, VR Device, …)

N/A

Author: Fantashit

4 thoughts on “TS: Vector3 interface not descriptive enough to support this valid usage

  1. Urgh! Let’s see if other TS devs figure out a different solution. If not, we can still make this change (and never look into the d.ts files again^^).

  2. From this stackoverflow answer it sounds like you could define fixed array types of a specific length and reuse them but I haven’t tested it:

    // ReusableTypes.d.ts
    export type Length3Array = [ number, number, number ];
    export type Length4Array = [ number, number, number, number ];
    export type Length16Array = [ /* ... */ ];
    
    // Vector3.d.ts
    class Vector3 {
    
        // ...
    
        toArray() : Length3Array;
    
    }
  3. I’ve used this syntax elsewhere:

    export type vec2 = [number, number];
    
    export type vec3 = [number, number, number];
    
    export type vec4 = [number, number, number, number];
    
    export type mat3 = [
    	number, number, number,
    	number, number, number,
    	number, number, number,
    ];
    
    export type mat4 = [
    	number, number, number, number,
    	number, number, number, number,
    	number, number, number, number,
    	number, number, number, number,
    ];

    There is no list/tuple distinction at runtime, this is just for typechecking.

  4. @Antony74 it sounds like you like @gkjohnson‘s proposal, but want to apply it only to Vectors and not to Matrices. Is that correct?

    The syntax above is one I have used with gl-matrix, see index.d.ts, where arrays are the basic unit of math operations, and used widely.

    I agree the case for a special type for matrices is weaker than the case for vectors. Mostly it’s just for consistency. But either way, I think this is a very minor syntax difference and should make no difference to the user’s code, as long as the case you described in the original post is handled?

Comments are closed.