Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
Function parameter in constructor

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
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda