rustyBucketBay
rustyBucketBay

Reputation: 4561

Avoid two time argument definition when passing function as argument typescript

As far as I researched, if you want a function to be passed as an argument and used as a callback, you need to introduce in the method all the arguments that the callback function is going to use, and then once again for those same arguments, when you define the type of callback function in the arguments, so twice.

In my code example below, arguments between two asterisks have to be defined twice, because most of the arguments are for the callback function, of whom types have to be once again defined when you define the callback itself (see the last argument callbackFunc):

keyBoardListenerSet: (**gl:WebGLRenderingContext**, 
    document:Document, **primitiveType: GLenum**,
    **offset: number**, **count: number**, **program:WebGLProgram**,
    pos: Float32Array, rot: Float32Array, anglesChanged: {x:boolean, y:boolean, z:boolean},
    callbackFunc: (gl:WebGLRenderingContext, primitiveType: GLenum, offset: number,
    count: number, program: WebGLProgram) => void): void => {
    

    //really meaningful code


}

I was trying to pass the function with the arguments already set in a variable, and delay execution in my function to avoid argument type definition, but I think that is not possible (I'm new to Javascript), so if this is not possible, is there any less verbose way to use callback functions as arguments in typescript (by this I mean, a way to avoid set the type twice for the same argument that will be used in the callback function)? Thanks

Upvotes: 0

Views: 235

Answers (1)

Catalyst
Catalyst

Reputation: 3227

You can refactor the type out into its own type declaration, and then you can also group the re-usable parameters into a single argument as an object:

e.g.


// could also be a Tuple if you don't want to type out param keys e.g. type A = [number, string]
type KeyboardListenerParam = {
    gl: WebGLRenderingContext,
    primitiveType: GLenum,
    offset: number,
    count: number,
    program: WebGLProgram,
    pos: Float32Array,
    rot: Float32Array,
    document: Document,
    anglesChanged: { x: boolean, y: boolean, z: boolean }
};

const something = {
    keyBoardListenerSet: (
        params: KeyboardListenerParam,
        callbackFunc: (params: KeyboardListenerParam) => void
    ): void => {
        window.requestAnimationFrame(() => {
            callbackFunc(params);
        });
        //really meaningful code
    }
}

Upvotes: 1

Related Questions