构造函数中的函数参数

Function parameter in constructor

我有一个class,它将一个符合接口的函数作为参数。 class 稍后使用给定的输入调用此函数。

在界面中,输入始终是必需的,但其他参数也是允许的,尽管是可选的。我想在创建实例时提供这些额外的参数 - 我应该怎么做?

我考虑过在将应用于函数调用的构造函数中添加一个 args 参数,但这看起来很难看,并且会从函数中分离参数。我还考虑创建一个中间函数,它采用单个 input 参数并将其传递给具有 args 的函数,但这又显得很混乱 - 我想将所有内容封装在 [=20= 中] 并在构造时提供结果实例的所有配置。

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

解决方案之一是将 repeatInput 更改为如下所示的函数创建器:

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