首页 > 解决方案 > How to annotate a generic closure that returns an object with methods with Flow?

问题描述

This throws an error. It seems like the generic type T is not in scope in the push method?


function entries<T>() {
  let entries: T[] = []

  return {
    push: (entry: T) => {
      entries.push(entry)
    }
  }
}

let e = entries<string>()

e.push("abc") // <---- ERROR HERE

That throws the error:

    14: e.push("abc")
               ^ Cannot call `e.push` with `"abc"` bound to `entry` because string [1] is incompatible with `T` [2]. [incompatible-call]
        References:
        14: e.push("abc")
                   ^ [1]
        6:      push: (entry: T) => {
                           ^ [2]

Here is the try flow link: https://flow.org/try/#0FAMwrgdgxgLglgewgAgKYRgJzqgzgHgBUA+ACgEpkBvYASABtUY0Ns8AuZQgbQF1kAvMj7A6mJmEwoatWgAcwuABadS6LAE9OhSgOLU6tZMfVtcAOgXK1rDeUMBfOk6fBGzVIJZYcBXD4gAczJ7YFRLRSVSACIAQwAjKGjyIA

标签: javascriptflowtype

解决方案


推荐阅读