0

I have a class which takes as a parameter a function which conforms to an interface. The class later calls this function with a given input.

In the interface an input is always required, but other parameters are also allowed, though optional. I want to provide these extra paramters when creating an instance - how should I do this?

I have considered adding an args parameter in the constructor which will be applied to the function call, but this seems ugly and detaches the parameters from the function. I also considered creating an intermediate function which takes the single input parameter and passes it on to the function with args, but again this seems messy - I'd like to encapsulate everything inside the class and provide all configuration of the resulting instance when it is constructed.

interface IThingAction {
    (input: string, ...args: any[]): boolean;
}

let printInput: IThingAction = (input: string) => {
    console.log(input);
}

let repeatInput: IThingAction = (input: string, iterations: number) => {
    for (var i = 0; i < iterations, i++) {
        console.log(input);
    }
}

class Thing {
    action: IThingAction;

    constructor(action: IThingAction) {
        this.action = action;
    }

    doAction(input: string): boolean {
        return this.action(input);
    }
}

let speaker = new Thing(printInput);
let echoer = new Thing(repeatInput); // I'd like to provide extra parameters here, e.g. (3)

speaker.doAction('hello');
// hello
echoer.doAction('-o');
// -o
// -o
// -o
0

1 Answer 1

2

One of solution is to change the repeatInput becomes a function creator like below:

type IThingAction =  (input: string) => boolean;

const makeRepeatInput = (iterations: number): IThingAction => (input) => {
    for (var i = 0; i < iterations; i++) {
        console.log(input);
    }
}

let echoer = new Thing(makeRepeatInput(3));
Sign up to request clarification or add additional context in comments.

1 Comment

I think this will resolve the issue - when I’m working again tomorrow I will check and mark as correct if so. Thank you.

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.