0

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.

2
  • what about doing it bar = foo; like typescriptlang.org/play/…. Commented Nov 17, 2019 at 5:24
  • 1
    What do you mean by adding function to new class? Do you want to use them and do you want to define them in new class? Commented Nov 17, 2019 at 5:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.