Is it possible to annotate arrays with custom properties?

I am trying to add type annotations to 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 could declare a new type called SuperArray , something like this:

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

( View at flowtype.org/try )

But that doesn't work either. I looked through the documents and looked through the documents and did not find the answer to

A) Is it generally supported?
B) if so, how to annotate it.

+5
source share
1 answer

Someone posted a useful and informative answer (which I voted for), but it seems to have gone missing - perhaps because I indicated that he didn’t answer the original question exactly, despite the fact that he was offering a nice workaround.

Anyway, they suggested rewriting the code to define SuperArray as a class that extends the array and adds the details ...

 class SuperArray extends Array<number> { superLevel: string } const foo = new SuperArray(); 

( Explore Flowtype.org/try )

This is a good, clean solution, but I was mostly interested in knowing whether it is possible to annotate the original template - for example, in the case when one is limited to writing an autonomous declaration to describe a third-party module.

+1
source

Source: https://habr.com/ru/post/1261391/


All Articles