Categories
TypeScript Answers

How to add strongly-typed functions as parameters possible in TypeScript?

Spread the love

Sometimes, we want to add strongly-typed functions as parameters possible in TypeScript.

In this article, we’ll look at how to add strongly-typed functions as parameters possible in TypeScript.

How to add strongly-typed functions as parameters possible in TypeScript?

To add strongly-typed functions as parameters possible in TypeScript, we write define a type to be a function with the type for each parameter and the return type of the function.

For instance, we write

type FunctionName = (n: inputType) => any;

class ClassName {
  save(callback: FunctionName): void {
    callback(data);
  }
}

to create the FunctonName type which is set to type with signature n of type inputType and returns any type data.

And then we set the save method in ClassName to FunctionName to use it.

Conclusion

To add strongly-typed functions as parameters possible in TypeScript, we write define a type to be a function with the type for each parameter and the return type of the function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *