Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript interface with indexer and other properties

Tags:

typescript

I'm trying to write a definition file for the server-side API of ArangoDB. This API exposes a db object that can be used to access the collections, but also perform database-level operations like running queries. So 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 that doesn't look valid 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 giving the indexer a type of ArangoCollection|ArangoCursor but it didn't help.

Am I hitting a limit of what can be modelled with an interface, or is there another way around?

Thanks in advance.

like image 698
ThomasWeiss Avatar asked Feb 26 '17 10:02

ThomasWeiss


1 Answers

You want to use intersection types. Try this:

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

type ArangoDatabase = ArangoDatabaseIndex & ArangoDatabaseQuery;
like image 60
Aviad Hadad Avatar answered Sep 21 '22 17:09

Aviad Hadad