N. Taylor Mullen
N. Taylor Mullen

Reputation: 18301

TypeScript interfaces that are used to "new" objects

First, this question first arose after working with Three.js where I tried/trying to build interfaces for the library for my own sake.

Anyways, lets say we have the JS code:

var foo = new THREE.Vector3(0,0,0);

In TypeScript you could represent the THREE object as:

interface IThreeJS {
    Vector3(x: number, y: number, z: number): any;
}

declare var THREE: IThreeJS;

However as you can see we have ': any' returning from Vector3. If I create a IVector3 interface and try doing 'new THREE.Vector3(0,0,0): IVector3' we get a 'new expression on valid on constructors'. Hence having to return 'any'

Right now the only alternative is to have the Vector3 object off of IThreeJS return 'any' and do:

var foo: IVector3 = new THREE.Vector3(0,0,0);

So, is there anyway to have my IThreeJS interface's Vector3 method have a constructor AND return an IVector3?

Upvotes: 4

Views: 2211

Answers (2)

user6600549
user6600549

Reputation:

export class Vector3 {

  x: number;
  y: number;
  z: number;


  constructor(x, y , z) {
    this.x = x;
    this.y = y;
    this.z = z;
  }

}

const position = new Vector3(0, 0, 0);

Good luck

Upvotes: 0

Fenton
Fenton

Reputation: 251142

You can declare classes and modules too:

declare module THREE {
    export class Vector3 {
        constructor(x: number, y: number, z: number);
    }
}

Upvotes: 5

Related Questions