22

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.

2

1 Answer 1

34

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.