facebook / facebook/flow

Per-method bound for T defined on class?

Open
#4,450 7 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

Let's say I'm extending `Array` and want to implement 2 additional methods

```js
export class Arr extends Array {
constructor(arr: T[]) { // create Arr from regular array
super()
arr.forEach(x => this.push(x))
}
filterMap(f: T => ?U): Arr {
const arr = this.map(f).filter(Boolean)
return new Arr(arr)
}
flatten(): Arr {
if (this.length == 0) return new Arr([])
else if (this[0] instanceof Arr) {
const arr = this.reduce((xs, x) => [...xs, ...x], [])
return new Arr(arr)
}
else throw new Error(`Must be an array of arrays`)
}
}
```
Now, `flatten` can't work for just any `this`. It can only flatten arrays of arrays. so `T: Arr`. This fails to typecheck because `...x` might not be iterable.

Is there a way to annotate this? I tried `this[0] instanceof Arr`, but flow isn't smart enough. My current workaround is to make a separate function (not method)
```js
export function flatten>(this_: Arr): Arr {
const arr = this_.reduce((xs, x) => [...xs, ...x], [])
return new Arr(arr) // typechecks correctly
}

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.