Typescript: How to declare a default export also being a UMD namespace?
Asked Answered
J

0

6

In typescript there's this syntax to declare a 'bundle' of all of a module's exports as a UMD global namespace. From the docs:

export function isPrime(x: number): boolean;
export as namespace mathLib;

This declares a UMD global mathLib that serves as a namespace for all of the 'real' exports in this module, so we can write the following:

<script>
    mathLib.isPrime(2);
</script>

Now I have an entry module with a default export, and I would like that default export to be this namespace. But I cannot seem to get it to work. For example:

my-module.d.ts

interface MyType {
    bar: number;
}

declare const Foo: MyType;
export default Foo;

I want to create both a module build for this so it can be used in other module environments:

import Foo from 'my-module'

use(Foo.bar).someHow()

... and also want the type of this default export to be the type of a UMD global that I can give the name Foo - the same name as the default export, so that the types of my module are used in non-module scripts:

<script>
    use(Foo.bar).someHow() // exactly the same
</script>

For my UMD bundle I have configured webpack with the output.library.export = 'default' setting, so in reality a perfectly fine bundle is created that makes usage as illustrated above possible. But I cannot figure out how to have any type completion, because if I write:

  declare const Foo: MyType;
  export default Foo;
+ export as namespace Foo;

I will only get type completion in my IDE if I write the following:

<script>
    use(Foo.default.bar).someHow()
</script>

This does make sense from a TS point-of-view (it namespaces all exports including the default export, after all), but is obviously wrong and undesired. I can't find any info on this, is it possible at all?

Jinni answered 14/4, 2021 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.