typescriptcocos2d-jscocoscreator

Add a function to a class defined inside a declared namespace (Typescript)


I'm trying to add a new function to an existing class Node defined inside the namespace cc. The namespace is declared as follows:

creator.d.ts

declare namespace cc {
   ...
   export class Node extends _BaseNode {
      ...
   }
   ...
}

And my extension function attempt looks like:

NodeExtension.ts

interface cc {
    Node: {
        getWorldPosition(): cc.Vec2;
    }
}
cc.Node.prototype.getWorldPosition = function (this: cc.Node)  {
    return this.parent.convertToWorldSpaceAR(this.getPosition());
};

But I'm getting the error "Property 'getWorldPosition' does not exist on type 'Node'" when trying to set the function.

The creator.d.ts declaration file belongs to the game development framework Cocos Creator.


Solution

  • You can add a function to a class inside a namespace by first creating an interface (Node) that is wrapped inside a namespace with the same name (cc) that is then wrapped inside a declare global statement and then by adding the interface method (getWorldPosition) to the .prototype property of the type you want to extend (cc.Node).

    Example

    declare global
    {
        namespace cc
        {
            interface Node
            {
                getWorldPosition(): cc.Vec2;
            }
        }
    }
    
    cc.Node.prototype.getWorldPosition = function(this: cc.Node)
    {
        return this.parent.convertToWorldSpaceAR(this.getPosition());
    };
    
    export {}
    

    Reference

    This solution was based on this answer: https://stackoverflow.com/a/53392268/5946094