Destructuring Objects as Function Parameters With Flow Types
In javascript, we often want to pass objects as arguments to our functions. Since ES6, we can destructure those object for better readability. Flow is a static type checker for javascript maintained by Facebook. Let’s look at integrating the two.
Object destructuring in ES6 functions looks like so:
function coolKids({name, isCool}) {
console.log(name, isCool);
}
coolKids({name: 'Rob', isCool: false});
// Rob, false
This is nice, as we can see when calling the coolKids function the key/value pairs. Much easier to gather what the function’s purpose is.
Now, let’s add some default values, which we can now do inside the function definition object itself!
function coolKids({name = 'The Dude', isCool = true}) {
...
}
Finally, we want to setup type checking using Flow. We can do that by mapping our object to a second type object.
function coolKids({name = 'The Dude', isCool = true}: {name: string, isCool: boolean) {
...
}
And there you have it! Some further reading on Flow types and destructuring for your learning pleasure.
Comments (4)
Leave a Reply
Unfortunatelly, Flow does not seems to get this when the type is not JSON.
As per your example:
type Kid = {
name: string,
isCool: boolean
}
function coolKids({name = ‘The Dude’, isCool = true}: Kid) { .. }
Now the name and isCool variables are untyped inside the coolKids function… Any idea on how to solve this?
Link to commentNice!
I’ve tried different syntaxes and stumbled into this exact one that seemed to work. Glad that this article confirms it is valid usage. Flow documentation seems far from being clear in that respect.
Link to commentAgreed. Anything remotely complicated is tough to follow in their docs. Glad this helped you!
Link to commentI totally agree. That’s what spawned the post actually.
Link to comment