Luka
Luka

Reputation: 4211

Typescript full-qualify namespace vs import what is the difference

Hi I have some problems understanding namespaces in Typescript... What is the difference between this:

export class FileBrowser {
    ...
    attached() {
        let elem = $("#file-manager");
        elem.dxFileManager({
            name: "fileManager",
            fileProvider: new DevExpress.fileProvider.RemoteFileProvider({
            })           
        });
    }
}

and this:

import RemoteFileProvider from 'devextreme/ui/file_manager/file_provider/remote';

export class FileBrowser {
    ...
    attached() {
        let elem = $("#file-manager");
        elem.dxFileManager({
            name: "fileManager",
            fileProvider: new RemoteFileProvider({                
            })           
        });
    }
}

So in the first one (that compiles but does not work!) I specify RemoteFileProvider with fully qualified namespace name and without importing it. Where in the second one (that works) I use import and then reference RemoteFileProvider without fully-qualify it.

The firs code does compile without problems, but then at runtime throws:

Uncaught (in promise) TypeError: Cannot read property 'RemoteFileProvider' of undefined

While the second one works flawlessly.

Update The declarations are:

declare module DevExpress {...}
declare module DevExpress.fileProvider {
    ...
    export class RemoteFileProvider extends FileProvider {
        ...
    }
}

Upvotes: 0

Views: 1012

Answers (1)

bela53
bela53

Reputation: 3485

The first example assumes you have declared a global namespace like:

namespace DevExpress {
    export namespace fileProvider {
        export class RemoteFileProvider {
            constructor(someProp: {}) {}
        }
    }
}

This namespace is embedded in a script file (not a module with import/export), is available on the global JS scope and can be used directly (doesn't have to be imported). You also could prepend window or globalThis to access RemoteFileProvider:

new window.DevExpress.fileProvider.RemoteFileProvider(/*your args*/)
// or
new globalThis.DevExpress.fileProvider.RemoteFileProvider(/*your args*/)           

In the second example, RemoteFileProvider is the default export member of the module remote with the absolute path 'devextreme/ui/file_manager/file_provider/remote':

export default class RemoteFileProvider {
    constructor(someProp: {}) {}
}

The firs code does compile without problems, but then at runtime throws [...] while the second one works flawlessly.

That sounds like your namespace definition has flaws (see above namespace as proper example) or you incorrectly assigned RemoteFileProvider to the global scope. This could also be a hint, that you have declared an ambient namespace declare namespace DevExpress (or similar), so there is no runtime equivalent code of the compiler declarations.

Upvotes: 1

Related Questions