squgeim
squgeim

Reputation: 2351

Defining types for untyped module that exports single function

I am using parse-diff in a TypeScript project. parse-diff does not contain a type definition, so I went about writing my own.

It exports a single function, like this:

exports = function () { /* ... */ }

and I include it in the script as:

import * as parse from 'parse-diff';

I got the definition to work by declaring a module. This is what I've got so far:

declare module 'parse-diff' {

  interface Change {
    type: string;
    normal: boolean;
    ln1: number;
    ln2: number;
    content: string;
  }

  interface Chunk {
    content: string;
    changes: Change[];
    oldStart: number;
    oldLines: number;
    newStart: number;
    newLines: number;
  }

  interface File {
    chunks: Chunk[];
    deletions: number;
    additions: number,
    from: string,
    to: string,
    index: string[]
  }

  function parse(diff: string): File[];

  namespace parse {}
  export = parse;
}

This works fine. The problem now is that I can't figure out how I could import and use the individual interfaces elsewhere.

If I import them from the package, I get the error:

"parse-diff" has no export member "File"

If I export the interfaces from the module, I'd have to export default the parse function. That way I get the error:

Cannot invoke an expression whose type lacks a call signature. Type 'typeof 'parse-diff'' has no compatible call signatures.

I just can't figure out how I can keep the "only one export" nature of the module and also use the internal interfaces.

Upvotes: 1

Views: 498

Answers (1)

lleon
lleon

Reputation: 2765

Edit your namespace and declare the interfaces inside it

declare module "parse-diff" {
  function parse(diff: string): parse.File[];

  namespace parse {
    interface Change {
      type: string;
      normal: boolean;
      ln1: number;
      ln2: number;
      content: string;
    }

    interface Chunk {
      content: string;
      changes: Change[];
      oldStart: number;
      oldLines: number;
      newStart: number;
      newLines: number;
    }

    interface File {
      chunks: Chunk[];
      deletions: number;
      additions: number;
      from: string;
      to: string;
      index: string[];
    }
  }
  export = parse;
}

Upvotes: 2

Related Questions