Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify function parameters for React component callback with TypeScript?

Tags:

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.

like image 538
Wilka Avatar asked Aug 11 '17 07:08

Wilka


People also ask

How do you pass callback function as parameter TypeScript?

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.

How do you pass parameters in callback function in React?

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.

How do you type a callback function in TypeScript?

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.

How do you pass parameters to a function in TypeScript?

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.


1 Answers

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.

like image 121
Wilka Avatar answered Nov 12 '22 23:11

Wilka