Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to annotate Arrays with custom properties?

I'm trying to add type annotations to an existing code and I have an Array instance that doubles as an object with custom properties set on it. Like So:

const foo = [];
foo[0] = 13;
foo.push(42);

foo.superLevel = 'extreme'; // Flow complains about this

I thought I might declare a new type called SuperArray, something along the lines of this:

type SuperArray = Array<number> & {
  superLevel: string,
}
const foo: SuperArray = [];
// ...

(View on flowtype.org/try)

But that doesn't work either. I've Goggled and browsed through the docs, and failed to find an answer as to

A) is this at all supported?
B) if so, how to annotate it.

like image 716
Már Örlygsson Avatar asked Nov 09 '22 04:11

Már Örlygsson


1 Answers

Someone posted a helpful and informative answer (that I up-voted) but it seems to have gone missing - perhaps because I pointed out that it didn't exactly answer the original question, despite offering a nice workaround.

Anyhow, they suggested rewriting the code to define SuperArray as a class that extends Array and adds props...

class SuperArray extends Array<number> {
  superLevel: string
}

const foo = new SuperArray();

(Explore on Flowtype.org/try)

It's a nice, clean way out, but I was mainly interested in finding out if annotating the original pattern was possible – like in a case where one is limited to writing a standalone declaration to describe a 3rd party module.

like image 125
Már Örlygsson Avatar answered Nov 14 '22 21:11

Már Örlygsson