facebook / facebook/flow

Per-method bound for T defined on class?

Offen
#4,450 7 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
Rust
Sterne
22.3k
Forks
1.9k
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

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
}

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.