如何使用TypeScript为React组件回调指定函数参数?

Wil*_*lka 10 typescript reactjs

我在TypeScript中有一个React组件,它看起来像这样:

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>
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够指定onDetailsChanged我的propTypes(FooSelectorProps)中的函数接受一个 FooDetails对象,但我无法弄清楚如何做到这一点.

Wil*_*lka 16

您可以改为使用类型的全局类型Function,而不是使用全局类型onDetailsChanged,因此请更改FooSelectorProps为:

interface FooSelectorProps {
    onDetailsChanged: ((details: FooDetails) => void)
}
Run Code Online (Sandbox Code Playgroud)

那么你将获得onDetailsChanged回调的类型检查.