How to export inner members of an existing Typescript declarations module

Let's say that I have a declarations file describing the shape of a node module that exports an object with multiple members. This file exists at foo/index.d.ts and looks like:

interface Foo {
  bar: () => void;
  // ... more members here
}


declare var Foo: Foo;
export = Foo;

With this, I can require and use the module as normal when compiling:

import * as Foo from 'foo';
Foo.bar();

However, I now want to also be able to do this:

import * as bar from 'foo/bar';
bar();

I've tried every possible combination of declaration file paths, modules, namespaces, and contexts, but I can't get this working. The most obvious, intuitive way would be to create a file at foo/bar/index.d.ts with:

import * as Foo from '..';
export = Foo.bar;

But doing this results in the error: 'Foo' only refers to a type, but is being used as a namespace here.

How can I create declaration files that define modules that export both outer and inner members?

Edit: Tried to use declare module as suggested by @cevek, but this throws the error "Cannot find namespace Foo":

declare module "foo/bar" {
  var bar: Foo.bar;
  export = bar;
}

1 answer

  • answered 2017-01-11 14:19 cevek

    You can use module declarations

    //foo.d.ts
        interface Foo {}
        interface Bar {}
    
        declare module 'foo' {
            export default Foo
        }
    
        declare module 'foo/bar'{
            export default Bar
        }
    

    And use it from another place

    import * as Foo from 'foo';
    import * as Bar from 'foo/bar';