facebook / facebook/flow

Per-method bound for T defined on class?

Aperta
#4,450 7 commenti 0 reazioni 0 assegnatari Vedi su GitHub
Lingua principale
Rust
Stelle
22.3k
Fork
1.9k
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Descrizione

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
}

Guida per i contributori

Apri la guida per i contributori

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.