基于键的流对象值

时间:2019-02-13 22:22:24

标签: javascript flowtype

使用流程时,我一直想输入以下内容:

type Item = {
  timestamp: number,
  status: { completed: boolean },
  data: string,
}

type Filter = {
  timestamp: number,
  status: { completed: boolean },
}

const FilterFns: {
  [key: $Keys<Filter>]: ($ElementType<Filter, key>, item: Item) => boolean
} = {
  timestamp: (timestamp, item) => timestamp === item.timestamp,
  status: (status, item) => status.completed === item.status.completed,
}

但是我得到了错误:

13:   [key: $Keys<Filter>]: ($ElementType<Filter, key>, item: Item) => boolean
                                                  ^ Cannot resolve name `key`.

如果相反,我将FilterFns定义为:

const FilterFns: {
  [key: $Keys<Filter>]: ($Values<Filter>, item: Item) => boolean
} = {
  timestamp: (timestamp, item) => timestamp === item.timestamp,
  status: (status, item) => status.completed === item.status.completed,
}

我得到了错误:

16:   status: (status, item) => status.completed === item.status.completed,
                                       ^ Cannot get `status.completed` because property `completed` is missing in `Number` [1].
References:
8:   timestamp: number,
                ^ [1]

确保以FilterFns值传递给函数的第一个参数是Filter中对应类型的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

不是对象键问题的一般解决方案,但是特殊情况可以用另一种方法解决

type Item = {
  timestamp: number,
  status: { completed: boolean },
  data: string,
}

type Filter = {
  timestamp: number,
  status: { completed: boolean },
}

const FilterFns: {
  [key: $Keys<Filter>]: ($Values<Filter>, item: Item) => boolean
} = {
  timestamp: (timestamp, item) => timestamp === item.timestamp,
  status: (status, item) => typeof status === 'object' && status.completed === item.status.completed,
}

添加附加条件typeof status === 'object'将使流程能够确定当前确切的值,否则流程将无法获取对键-不幸的是,值正确