I have a React component in TypeScript that looks something like this:
interface FooDetails { name: string latitude: number, longitude: number, } interface FooSelectorProps { onDetailsChanged: Function, } class FooSelector extends React.Component<FooSelectorProps, any> { constructor(props: FooSelectorProps, context) { super(props, context); } onTravelTypeChange(event) { this.setState({ travelType: event.target.value }); } onDetailsChange(fooData) { this.props.onDetailsChanged({ name: fooData.name, latitude: fooData.latitude, longitude: fooData.longitude, }); } render() { return <div>...Foo selection UI...</div> } }
I'd like to be able to specify that the onDetailsChanged
function in my propTypes (FooSelectorProps
) takes a FooDetails
object, but I can't figure out how to do that.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.
Use Type Keyword to Declare Callback Type in TypeScript In TypeScript, the type keyword declares a type alias. So with the help of the type keyword, you could declare your callback type as shown below. type callBackFunction = () => void; This declares a function that does not take any arguments and returns nothing.
Master Typescript : Learn Typescript from scratch Parameters form a part of the function's signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined.
Instead of using the global type Function
for type of onDetailsChanged
, you can write out the type instead, so change FooSelectorProps
to:
interface FooSelectorProps { onDetailsChanged: ((details: FooDetails) => void) }
then you'll get type checking for the onDetailsChanged
callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With