Home > Mobile >  Can you set a type for a function in typescript?
Can you set a type for a function in typescript?

Time:05-09

I want for a function to implement a certain type of interface, to have a certain type of signature. The same way you would implement an object.

Say I have an interface like this:

interface IStrategyOptionsWithRequest {
    usernameField?: string | undefined;
    passwordField?: string | undefined;
    session?: boolean | undefined;
    passReqToCallback: true;
}

I can quickly determine that passReqToCallBack is required if I give the type IStrategyOptionsWithRequest to the instance that I'm creating.

let localStrategyOptions : IStrategyOptionsWithRequest  = {
    passReqToCallback: true
}

Say I have another interface like this:

interface VerifyFunctionWithRequest {
    (
        req: express.Request,
        username: string,
        password: string,
        done: (error: any, user?: any, options?: IVerifyOptions) => void
    ): void;
}

How can I now create a function that is of type VerifyFunctionWithRequest? This would be useful so that I'm certain that the function I'm creating has the correct signature.

I did try

function verify: VerifyFunctionWithRequest (){
    
}

which gives me:

'(' expected.

Is this even a thing or am I thinking about this the wrong way?

Edit: Clarifying that I'm interested that the IDE would give me a linting error in the case I'm not implementing the function correctly.

CodePudding user response:

You can use the function type like this:

const verify: VerifyFunctionWithRequest =
  function (req, username, password, done) {

  };

CodePudding user response:

What you could do is use a builder function that builds your requested function for you, in that case you are guaranteed to have a specific layout. Here is an example of this:

type VerifyFunctionWithRequest = (
    req: unknown,
    username: string,
    password: string,
    done: (error: any, user?: any, options?: unknown) => void
) => void;

const verify = ((): VerifyFunctionWithRequest => 
    (req, username, password, done) => {
        // Your "verify" function goes here
    }
)()

// Use verify as usual
verify(req, "username", "password", () => console.log("Done"))
  • Related