Skip to content

Instantly share code, notes, and snippets.

@florapdx
Last active January 24, 2018 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florapdx/5d2bf7b3abba5d5038d1f318b2ffed87 to your computer and use it in GitHub Desktop.
Save florapdx/5d2bf7b3abba5d5038d1f318b2ffed87 to your computer and use it in GitHub Desktop.
how do I type the cb?
/*
In the scenario below, I have a menu that can be used to render a list
of selectable options that may be of type 'string' or of type 'number'.
It takes a 'onOptionSelect' callback whose arguments can be of either type.
However, some components that render this generic menu may only accept
string-type selections or may only accept number-type selections. How do I
type onOptionsSelect (or the actual callbacks that get passed in) to account
for this flexibility?
*/
// generic-menu.js
type Props = {
options: Array<string | number>,
onOptionSelect: (option: string | number) => void
}
function MyMenu(props: Props) {
const { onOptionSelect } = this.props
return (
<div className="menu">
<ul>
{options.map((option, idx) => (
<li key={idx}>
<button onClick={onOptionSelect}>{option}</button>
</li>
))}
</ul>
</div>
)
}
// mypage.js
class MyPage extends Component {
handleSelect = (name: string) => { // this line will have a Flow error since I'm not allowing number types for name arg
api.post(..., { name })
}
render() {
return (
<div>
<h1>My name-picker page</h1>
<MyMenu
options={['tina', 'tammy', 'toby']}
onOptionSelect={this.handleSelect}
/>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment