3

I am using Typescript and I am trying to add a variable to another library (Babylonjs). I know in javascript I could freely just add any variable to an object and it would let me do it. Typescript is notifying me that that I can't. Part of the joy I suppose that it notifies you, but in this case I want to do it.

For example:

var mesh = BABYLON.Mesh('name', scene);
mesh.myVariable = 'tada!';

Now myVariable is not part of BabylonJS Mesh class. How can I add a typedef file to say, sure it is. (I will be sure to check every time I access myVariable that it has been set)

I have tried:

declare module BABYLON{
  export interface Mesh {
    myVariable : any;
  }
}

and typescript is being kind in letting me know Duplicate identifier 'Mesh'. In the Babylon typedef file, Mesh is declared as:

declare module BABYLON {
  class Mesh extends AbstractMesh implements IGetSetVerticesData {
  ...
  }
}
Chris R
  • 276
  • 2
  • 7

1 Answers1

2

To add something dynamically as a one-off, you can do this:

(<any>mesh).myVariable = 'tada!';

You'll have to do that anywhere you want to read or write to it though.

What you might want to consider though is what it appears you are doing...extending an object with new capabilities. In typescript, I do this by defining a new class that extends the one I'm working with and adds the new functionality. Something like:

    module myModule {
      export class MyMesh extends BABYLON.Mesh {
        public var myVariable:string;
      }
    }

You can now write a getter and setter or add new methods etc.

If you are passing your typed instance into some method that requires the original (BABYLON.Mesh), you would have to downcast it accordingly:

someFunctionThatTakesMeshParam( <BABYLON.Mesh>myMesh );

There is some more discussion here: How do I dynamically assign properties to an object in TypeScript?

Community
  • 1
  • 1