Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda