简体   繁体   中英

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.

You need to also do something like:

interface UsersBlocksMyOrders {
    myFunc(): any;
}

Otherwise the compiler doesn't know about it.


Edit

It does indeed work, even with existing classes.
For example:

interface String {
    logit(): void;
}

String.prototype.logit = function () {
    console.log(this);
}

let a = "string";
a.logit();

( code in playground )

If you'll add more relevant information it will be easier to help you.


2nd Edit

You said nothing about importing.
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); }

But I've never tried it with relative paths, and why would you need to?
It's your source code, you can change it directly in pages/users/blocks/myorders , doing it like you're trying to isn't a good idea.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM