admin管理员组

文章数量:1289581

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

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

But piler give me a error.

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

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

But piler give me a error.

Share Improve this question edited Apr 1, 2018 at 13:13 Eymen Elkum 3,1411 gold badge21 silver badges35 bronze badges asked Dec 22, 2016 at 16:10 Alexander ZakusiloAlexander Zakusilo 1,5664 gold badges18 silver badges34 bronze badges 4
  • What error it gives? – elclanrs Commented Dec 22, 2016 at 16:13
  • What's your purpose for dynamically extending a class? – timothyclifford Commented Dec 22, 2016 at 16:15
  • Error: Property 'myFunc' does not exist on type 'UsersBlocksMyOrders' – Alexander Zakusilo Commented Dec 22, 2016 at 16:19
  • I need dynamically extend class because I want to give to anyone extend with external javascript to add methods. – Alexander Zakusilo Commented Dec 22, 2016 at 16:22
Add a ment  | 

2 Answers 2

Reset to default 6

Most often, you need to do something like:

interface UsersBlocksMyOrders {
    myFunc(): any;
}

Otherwise the piler 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.

This may help (from here):

function extend<T, U>(first: T, second: U): T & U {
    let result = <T & U>{};
    for (let id in first) {
        (<any>result)[id] = (<any>first)[id];
    }
    for (let id in second) {
        if (!result.hasOwnProperty(id)) {
            (<any>result)[id] = (<any>second)[id];
        }
    }
    return result;
}

class Person {
    constructor(public name: string) { }
}
interface Loggable {
    log(): void;
}
class ConsoleLogger implements Loggable {
    log() {
        // ...
    }
}
var jim = extend(new Person("Jim"), new ConsoleLogger());
var n = jim.name;
jim.log();

本文标签: javascriptHow to dynamically extend class with method in TypeScriptStack Overflow