1

i need to extend a prototype, creating methods by mapping a set of strings into a single function. however, i'm having trouble extending a class prototype even for a base case. e.g.:

class Hello {}
Hello.prototype['whatever'] = 1
// [ts] Element implicitly has an 'any' type because type 'Hello' has no index signature.

i read here about index signatures, but not sure how to extend the prototype's definition?

really, i want something pretty simple, similar to as follows:

const methods = ['a', 'b', 'c']
const exampleMethodImplementation = () => 'weeee'
class Hello {
   x: number
}
methods.forEach(name => { Hello.prototype[name] = exampleMethodImplementation })

1 Answer 1

1

One option is to declare the class with "dynamic" properties.

class Hello {
    [prop: string]: any;
}

Another option is to use 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

But you'll need to make sure that the interface properties and array elements stay synchronized.

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

2 Comments

thanks. though this could work, practically it does not if you use other properties on your class that don't fit that fn signature. i will update the example class with another property to demonstrate.
Correct, but you could use any instead of the function signature. I updated my answer with a "more complete" solution, but it does require a bit of repetition.

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.