Export additional interfaces for CommonJS module (Typescript)

Viewed 1380

I'm trying to use a simple JS library in Typescript/React, but am unable to create a definition file for it. The library is google-kgsearch (https://www.npmjs.com/package/google-kgsearch). It exports a single function in the CommonJS style. I can successfully import and call the function, but can't figure out how to reference the type of the arguments to the result callback.

Here is most of the library code:

function KGSearch (api_key) {
  this.search = (opts, callback) => {
    ....
    request({ url: api_url, json: true }, (err, res, data) => {
      if (err) callback(err)
      callback(null, data.itemListElement)
    })
    ....
    return this
  }
}

module.exports = (api_key) => {
  if (!api_key || typeof api_key !== 'string') {
    throw Error(`[kgsearch] missing 'api_key' {string} argument`)
  }

  return new KGSearch(api_key)
}

And here is my attempt to model it. Most of the interfaces model the results returned by service:

declare module 'google-kgsearch' {

    function KGSearch(api: string): KGS.KGS;
    export = KGSearch;

    namespace KGS {

        export interface SearchOptions {
            query: string,
            types?: Array<string>,
            languages?: Array<string>,
            limit?: number,
            maxDescChars?: number
        }

        export interface EntitySearchResult {
            "@type": string,
            result: Result,
            resultScore: number
        }

        export interface Result {
            "@id": string,
            name: string,
            "@type": Array<string>,
            image: Image,
            detailedDescription: DetailedDescription,
            url: string
        }

        export interface Image {
            contentUrl: string,
            url: string
        }

        export interface DetailedDescription {
            articleBody: string,
            url: string,
            license: string
        }

        export interface KGS {
            search: (opts: SearchOptions, callback: (err: string, items: Array<EntitySearchResult>) => void) => KGS.KGS;
        }
    }
}

My issue is that from another file I am unable to reference the KGS.EntitySearchResult array returned by the search callback. Here is my use of the library:

import KGSearch = require('google-kgsearch');
const kGraph = KGSearch(API_KEY);

interface State {
    value: string;
    results: Array<KGS.EntitySearchResult>; // <-- Does not work!!
}

class GKGQuery extends React.Component<Props, object> {    

    state : State;

    handleSubmit(event: React.FormEvent<HTMLFormElement>) {
        kGraph.search({ query: this.state.value }, (err, items) => { this.setState({results: items}); });
        event.preventDefault();
    }
    ....
}

Any suggestions for how to make the result interfaces visible to my calling code without messing up the default export is very greatly appreciated.

1 Answers
Related