Typescript interface with index and other properties

I am trying to write a definition file for the ArangoDB server API. This API provides a db object that can be used to access collections, but also perform database-level operations, such as executing queries. Therefore, I can call:

 db['my-collection'] <- returns a collection object 

but also:

 db._query('some query') <- returns a query cursor 

So, I tried the following interface:

 interface ArangoDatabase { [collectionName: string]: ArangoCollection; _query(query: string): ArangoCursor; } 

but this does not apply to TS, as it generates the following error:

 Property '_query' of type '(query: string) => ArangoCursor' is not assignable to string index type 'ArangoCollection'. 

Note. I tried this solution by specifying the index type ArangoCollection|ArangoCursor , but that did not help.

Am I finding the limit of what can be modeled using an interface, or is there another way?

Thanks in advance.

+5
source share
2 answers

You want to use intersection types. Try the following:

 interface ArangoDatabaseIndex { [collectionName: string]: ArangoCollection; } interface ArangoDatabaseQuery { _query(query: string): ArangoCursor; } type ArangoDatabase = ArangoDatabaseIndex & ArangoDatabaseQuery; 
+6
source

The query member type (query: string)=>ArangoCursor , so the ArangoCollection|ArangoCursor union did not work for you.

It should be:

 interface ArangoDatabase { [collectionName: string]: ArangoCollection|((query: string)=>ArangoCursor); _query(query: string): ArangoCursor; } 
+3
source

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


All Articles