将现有函数作为方法添加到类中

问题描述 投票:0回答:1

我有两个例子,我有一组这样的功能:

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

另一个只是一个独立的功能:

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

如何将它们添加到现有的类中:

class Example {

}

我对装饰器开放,理想情况下,我不必打开构造器。

typescript es6-class
1个回答
0
投票

我认为您可以在运行时通过将其添加到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"));

这种方法的症结在于,这些方法是在运行时添加的。因此,打字稿编译器不知道它们存在于示例的原型中。

[我认为如果使用打字稿,这不是我们应该做的事情,因为打字稿的唯一目的是在编译时检查内容。

© www.soinside.com 2019 - 2024. All rights reserved.