⭐ Typing Functions ⭐
We have an addListener function here:
const addListener = (onFocusChange: unknown) => {
window.addEventListener("focus", () => {
onFocusChange(true);
});
window.addEventListener("blur", () => {
onFocusChange(false);
});
}
The type of onFocusChange that is passed in is currently unknown.
We want it to be a function that will take in a single boolean argument.
🌟 Solution: Specify the Type of a Function
We can declare a function type using this syntax:
(isFocused: boolean) => void
The isFocused argument is a boolean, and we are returning void.
This syntax can be used inline like this:
const addListener = (onFocusChange: (isFocused: boolean) => void) => {
Or it can be extracted to its own type like this:
type FocusListener = (isFocused: boolean) => void;
const addListener = (onFocusChange: FocusListener) => {
The basic structure starts with the arguments and the return type, both of which can be whatever you want.
We can use undefined for the return type, but then our function has to actually return undefined.
For times when our function has no return value, we should use void.
Here is an example of adding an isGreat boolean as an additional argument:
type FocusListener = (isFocused: boolean, isGreat: boolean) => void;
Then whenever we called the FocusListener we would have to include parameters for both:
const addListener = (onFocusChange: FocusListener) => {
onFocusChange(true, true)
}
We can also use function types in the same way we are used to using other types. Just be aware that your return types match appropriately.
const myFocusListener = (isFocused: boolean): void => {
// TypeScript error that `{}` is unassignable to void
return {}
}
Most of the time, we are not going to need these types unless we are passing functions to other functions or declaring the type of the function.
I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Top comments (0)