首页 > 解决方案 > 如何将 typescript 类原型从映射到单个函数的字符串数组扩展

问题描述

我需要扩展一个原型,通过将一组strings 映射到单个函数来创建方法。但是,即使对于基本案例,我也无法扩展类原型。例如:

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 })

标签: typescript

解决方案


一种选择是声明具有“动态”属性的类。

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

但是您需要确保接口属性和数组元素保持同步。


推荐阅读