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

时间:2017-08-11 07:16:23

标签: reactjs typescript

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

  /cards/count:
    get:
      tags:
      - "cards"
      summary: "Number of Cards available"
      description: "Excludes cards which the user has answered correctly in the past."
      operationId: "countCards"
      produces:
      - "application/json"
      parameters:
      - name: "tagFilter"
        in: "query"
        description: "Input is optional - left blank will return all tags and a count"
        type: "object"
        properties:
          tags_any:
            type: "array"
            items:
              type: "integer"
              format: "int64"
              enum: [1,2,3]
          tags_all:
            type: "array"
            items:
              type: "integer"
              format: "int64"
              enum: [4,5,6]
          tags_not:
            type: "array"
            items:
              type: "integer"
              format: "int64"
              enum: [4,5,6]

我希望能够指定我的propTypes(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> } } )中的onDetailsChanged函数采用FooSelectorProps个对象,但我无法弄清楚如何做到这一点。

1 个答案:

答案 0 :(得分:11)

您可以改为将Function更改为:{/ 1>,而不是将全局类型onDetailsChanged用于FooSelectorProps类型,而是将其写出来。

interface FooSelectorProps {
    onDetailsChanged: ((details: FooDetails) => void)
}

然后您将获得onDetailsChanged回调的类型检查。