This article is relevant for all typescript
users.
Though, I haven't encountered this issue in Node.js
yet..
If you want you can skip the background part, and jump straight to the code examples.
Motivation
Recently I faced a new challenge with typescript
, in my react-redux
app.
One of the fundamental principles of react-redux
is separation of concerns.
As a result of this separation we might need to pass a lot of parameters to an action creator.
In addition, we might want to use this action creator
from different components
.
Until now everything sounds normal.
Now lets add Typescript
.
Adding typescript
to react-redux
app, forces us to define every action creator
function that we use in our component.
of-course some of the functions can be defined as Function
type, but there are a lot of places that we need the full function signature.
This boilerplate can be frustrating sometimes, especially when the team is getting bigger, and more people are starting to touch the code.
Me and my teammate Lidor Levy looked for a solution for this problem and found resolution in this Github issue.
Typescript is giving the option to inherit the parameters of a function!!
This is how we do it
Define your function wherever you want
export const YOUR_FUNCTION_NAME = (
param1: number,
param2: Array<SOME_INTERFACE>,
param3: string,
param4: boolean
): YOUR_FUNCTION_TYPE => {
// some logic, or even keep empty
}
In your function type definition
YOUR_FUNCTION_NAME: (
...YOUR_FUNCTION_NAME_Params: Parameters<
typeof YOUR_FUNCTION_NAME
>
) => YOUR_FUNCTION_TYPE
Don't forget to import
your function definition.
Now, when you use the function, typescript
will know the parameter types, and your IDE code-completion can help you regularly.
Enjoy!
Top comments (0)