带有泛型类型的绑定类方法

时间:2018-03-30 17:38:34

标签: flowtype

以下是tryflow

上的问题演示

基本上我有一个类可以运行一系列基本类型的物品。

type Props<ItemType> = {
  items: ItemType[],
  onSelect: (item: ItemType) => void
}

class List<ItemType> {
  props: Props<ItemType>
  activeIndex: number
  constructor(props: Props<ItemType>) {
    this.props = props;
    this.activeIndex = 0;
  }

  getActiveItem() : ?ItemType {
    return this.props.items[this.activeIndex];
  }

  submitItem(item: ?ItemType){
    if(item) {
      this.props.onSelect(item)
    }
  }

  onClick() {
    this.submitItem(this.getActiveItem())
  }
}


let numbers: number[] = [1,2,3];
let onSelect = (value: number) => {};

let numberList: List<number> = new List({ items: numbers, onSelect: onSelect})

这个例子来自一个反应组件,我将其拆除以更清楚地证明问题。

当我将submitItem()转换为绑定方法时,它主要起作用但遇到了问题:

  submitItem = (item: ?ItemType)  => {
    if(item) {
      this.props.onSelect(item)
    }
  }

这会导致以下错误:

27:     this.submitItem(this.getActiveItem())
                        ^ Cannot call `this.submitItem` with `this.getActiveItem()` bound to `item` because `ItemType` [1] is incompatible with `ItemType` [2].
References:
8: class List<ItemType> {
              ^ [1]
20:   submitItem = (item: ?ItemType)  => {
                           ^ [2]

该方法需要绑定到类,因为它将作为DOM事件的回调触发。

如何获取绑定方法以理解泛型类型。

1 个答案:

答案 0 :(得分:2)

property initialiser syntax(确保方法绑定到this的{​​{3}})没有创建与使用常规类属性时相同的类型签名时出现问题。我recommended method有一个简化的例子。

但是,在您的示例中,您似乎不需要执行此操作,因为您的onClick方法是需要绑定并作为事件处理程序传递的方法

// ...
submitItem(item: ?ItemType): void {
  if(item) {
    this.props.onSelect(item)
  }
}
onClick = () => {
  this.submitItem(this.getActiveItem())
}
// ...
相关问题