我需要扩展原型,通过将一组string
映射到单个函数中来创建方法。但是,即使在基本情况下,我也无法扩展类原型。例如:
class Hello {}
Hello.prototype['whatever'] = 1
// [ts] Element implicitly has an 'any' type because type 'Hello' has no index signature.
我读过here有关索引签名的信息,但不确定如何扩展原型的定义吗?
真的,我想要一些简单的东西,类似于以下内容:
const methods = ['a', 'b', 'c']
const exampleMethodImplementation = () => 'weeee'
class Hello {
x: number
}
methods.forEach(name => { Hello.prototype[name] = exampleMethodImplementation })
答案 0 :(得分:1)
一种选择是使用“动态”属性声明该类。
class Hello {
[prop: string]: any;
}
另一种选择是使用Declaration Merging。
type FuncA = () => string;
interface A {
a1: FuncA;
a2: FuncA;
a3: FuncA;
}
type FuncB = (value: string) => string;
interface B {
b1: FuncB;
b2: FuncB;
b3: FuncB;
}
class Hello {
constructor(public x: number) { }
}
interface Hello extends A, B { }
['a1', 'a2', 'a3'].forEach((method: string) => {
Hello.prototype[method as keyof A] = function (): string {
return 'FuncA';
};
});
['b1', 'b2', 'b3'].forEach((method: string) => {
Hello.prototype[method as keyof B] = function (value: string): string {
return `FuncB: ${value}`;
};
});
const hello = new Hello(1);
console.log(hello.a1()); // FuncA
console.log(hello.b1('foo')); // FuncB: foo
但是您需要确保接口属性和数组元素保持同步。