Marcelo Iepsen
Marcelo Iepsen

Reputation: 43

Is it possible to describe a remote javascript as a typescript module with .d.ts file?

I'm was trying to describe a remote javascript as a typescript module with a .d.ts file but I got an error message

Module not found: Can't resolve 'player' in '/Users/iepsen/project/src'.

It happens because it trying to load a local module.

So how can I load a remote javascript and let typescript know their methods and param types?

src/types/globals.d.ts

declare module 'player' {
    namespace player {
        function constructor(param1: string, param2: string): void
        function play(): void
    }
    export = player
}

src/index.tsx

import * as Player from 'player';
Player.play();

Upvotes: 3

Views: 604

Answers (1)

casieber
casieber

Reputation: 7542

Since this player module isn't something actually included with your code when you build, you will need to declare it and use it as an Ambient Namespace.

See the last paragraph in Typescript's Namespaces documentation for their description of Ambient Namespaces.

In essence, you need to modify your .d.ts file to:

declare namespace Player {
    export interface Base {
        function constructor(param1: string, param2: string): void;
        function play(): void;
    }
}

declare var Player: Player.Base;

and then in your index.tsx

// No need for import, as it's an ambient module
Player.play();

Upvotes: 1

Related Questions