9

I have a small ts library that gets outputed as UMD and I also output the *.d.ts file automatically via tsconfig: "declaration": true.

The file being exported looks like:

export class Blue { 
    alert(): void {
        console.log('alerted');
    }
}

Using exported UMD module declares a window.myLib variable.

The d.ts file looks like:

export declare class Blue {
    alert(): void;
}

Now, either via webpack, or a typescript option that I have not found I would like to also generate in the d.ts file the following line:

export as namespace myLib;

Is there a way to do this? Thanks.

1 Answer 1

2

Instead of just:

export class Blue { 
    alert(): void {
        console.log('alerted');
    }
}

Try:

class Blue_ { 
  alert(): void {
      console.log('alerted');
  }
}

export { Blue_ as Blue };

declare global {
  namespace myLib {
    let Blue: typeof Blue_;
  }
}

This would spit the following declaration file:

declare class Blue_ {
    alert(): void;
}
export { Blue_ as Blue };
declare global {
    namespace myLib {
        let Blue: typeof Blue_;
    }
}

Now myLib.Blue is accessible globally, and also, class Bluecould be imported like import { Blue } from '...'. Which is equivalent to having export as namespace myLib; in the declaration file.

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

This solution is perfect, and it overcomes the current limitation of nested namespace in the "export as namespace" support: github.com/microsoft/TypeScript/issues/20990

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.