ThomasReggi
ThomasReggi

Reputation: 59355

Adding existing functions to a class as methods

I have two examples one I have a group of functions like this:

const funcs = () => {
    const foo = (t: string) => `${t} meow`
    const bar = (t: string) => `${t} woof`
    return { foo, bar }
}

The other is just a stand alone function:

const foo = (t: string) => `${t} meow`

How can I add these to an existing class:

class Example {

}

I'm open to decorators, ideally I don't have to open up the constructor.

Upvotes: 0

Views: 59

Answers (1)

vibhor1997a
vibhor1997a

Reputation: 2376

I think that you would be able to add those methods at the run time by adding it to the prototype of Example

const funcs = () => {
    const foo = (t: string) => `${t} meow`
    const bar = (t: string) => `${t} woof`
    return { foo, bar }
};

class Example {
    [prop: string]: any;
}

let fns:{[prop: string]: any;} = funcs();

for (let key of Object.keys(fns)) {
    let fn = fns[key];
    Example.prototype[key] = fn;
}

console.log(new Example().bar("hello"));

The crux for this way is that these methods are added at runtime. So, the typescript compiler doesn't know they even exist in example's prototype.

I think that this isn't something we shoud do if we're using typescript because typescript's sole purpose is to check stuff at compile time.

I believe the best way is to refractor it if you're using typescript.

Upvotes: 1

Related Questions