Search code examples
javascripttypescriptinheritanceprototype

How to dynamically extend class with method in TypeScript?


How to dynamically extend class with method in TypeScript? Any examples? I try:

UsersBlocksMyOrders.prototype.myFunc = function():any{
  alert('23434');
};

But compiler give me a error.


Solution

  • Most often, you need to do something like:

    interface UsersBlocksMyOrders {
        myFunc(): any;
    }
    

    Otherwise the compiler doesn't know about it.


    It even works with existing classes. For example:

    interface String {
        logit(): void;
    }
    
    String.prototype.logit = function () {
        console.log(this);
    }
    
    let a = "string";
    a.logit();
    

    (code in playground)


    Because you want to change something in a different module, which is called Module Augmentation, you need to do something like:

    Import { UsersBlocksMyOrders } from "../pages/users/blocks/myorders";
    
    declare module "../pages/users/blocks/myorders" {
        interface UsersBlocksMyOrders {
            logit(): void;
        }
    }
    
    UsersBlocksMyOrders.prototype.logit = function () { console.log(this); }
    

    Whenever possible (which it seems to be for you), edit the source code directly. Doing it like this should only be done on an as-needed basis.