Photo by Thomas Tastet on Unsplash
How to quickly find the right TypeScript parameter types in React
A beginner-oriented quick guide to safely identify a function's TypeScript parameter type when interacting with various elements in React
๐ What you'll get from this 2-minute read
- You'll get to know a quick way to identify the proper fit for a lot of function parameters when interacting with different elements.
- You'll establish more self-confidence for your future TypeScript projects.
๐ Identifying the appropriate type for function parameters
In this case, I'm trying to create a function in order to utilize a GSAP animation. In order to make this happen, we could use an object parameter that is connected to the current target. Let's say we want to animate a h1
element with an onClick
approach:
<h1 onClick={clickFunction}>test</h1>
After that, I am creating clickFunction
with the following approach:
const clickFunction = ({ currentTarget }): void => {
gsap.to(currentTarget, { transform: 'translateX(50px)' });
}
It looks good for now, right? But wait! TypeScript is screaming at us with a problem:
Since we are using TypeScript, we have to specify the type of parameter which we are using - in this case, for the object with currentTarget
.
As we are pretty new to TypeScript, we probably don't know off the top of our heads which type we have to use in this situation. However, there is a quick way to find out!
By adjusting the way we are invoking the clickFunction
at the h1
element, we are able to find the proper fit for this case:
As soon as we added a parameter to the inline code, we were able to hover over the e
parameter and get this information from above: (parameter) e: React.MouseEvent<HTMLHeadingElement, MouseEvent>
.
Now we can go back to our original function and add this type to the function's argument:
After this step, we will see that TypeScript has stopped screaming and our code will work.
You will experience that the type changes when you are interacting with different elements (Here we are specifically using a HTMLHeadingElement
with h1
). However, even for form, input, or other elements, this way will help you to quickly find the proper parameter types in TypeScript.
โ Conclusion
While this approach is - of course - not the fastest one, it's definitely a neat way for TypeScript beginners to overcome such starting problems when migrating from JavaScript to TypeScript.