typescript - 如何将 typescript 类原型从映射到单个函数的字符串数组扩展
问题描述
我需要扩展一个原型,通过将一组string
s 映射到单个函数来创建方法。但是,即使对于基本案例,我也无法扩展类原型。例如:
class Hello {}
Hello.prototype['whatever'] = 1
// [ts] Element implicitly has an 'any' type because type 'Hello' has no index signature.
我在这里阅读了有关索引签名的信息,但不确定如何扩展原型的定义?
真的,我想要一些非常简单的东西,类似于如下:
const methods = ['a', 'b', 'c']
const exampleMethodImplementation = () => 'weeee'
class Hello {
x: number
}
methods.forEach(name => { Hello.prototype[name] = exampleMethodImplementation })
解决方案
一种选择是声明具有“动态”属性的类。
class Hello {
[prop: string]: any;
}
另一种选择是使用声明合并。
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
但是您需要确保接口属性和数组元素保持同步。
推荐阅读
- angular - 在一个 Azure Blob 存储上托管多个 Angular 应用
- wordpress - 带有 Docker-Compose 和 AWS RDS MySQL 数据库的 AWS EC2 上的 WordPress
- airflow - 气流将 jinja 模板传递给 dag 参数
- r - ggplot:使用最小值和最大值的分类值添加 geom_rect
- windows - 无法运行 Windows docker 容器中路径中的可执行文件
- c# - 通信对象 System.ServiceModel.ChannelFactory` 不能用于通信,因为它处于故障状态
- amazon-web-services - 如何使用 serverless-offline 检测无服务器框架功能是否离线运行?
- swift - TabView 在第一次查看 SwiftUI 时不显示文本
- c# - 为什么在 for 循环的每次迭代中实例化一个新对象会覆盖以前的列表条目?
- python - 如何在熊猫的一个图形上绘制两个不同的图形?