CherryQu
CherryQu

Reputation: 3383

Import JS web assembly into TypeScript

I'm trying to use wasm-clingo in my TypeScript React project. I tried to write my own d.ts file for the project:

// wasm-clingo.d.ts
declare module 'wasm-clingo' {
  export const Module: any;
}

and import like this:

import { Module } from 'wasm-clingo';

but when I console.log(Module) it says undefined. What did I do wrong?

Notes:

Solution:

I solved the problem like this:

// wasm-clingo.d.ts
declare module 'wasm-clingo' {
  const Clingo: (Module: any) => Promise<any>;
  namespace Clingo {}
  export = Clingo;
}

and

import * as Clingo from 'wasm-clingo';

Here's the source for this solution

Upvotes: 1

Views: 3921

Answers (2)

see sharper
see sharper

Reputation: 12035

I know you found a solution acceptable to you; however, you don't really have any types here, you just have Module declared as any, which gives you no typescript benefits at all. In a similar situation I used @types/emscripten, which provides full type definitions for web assembly modules compiled using emscripten. You simply need to do:

npm install --save-dev @types/emscripten

then change your tsconfig.json types array to add an entry for emscripten. After that you can just write Module.ccall(...) etc. If you like you could of course write const Clingo = Module and then make calls against that if you want a more descriptive name than Module (which is a terrible name!).

You're welcome ;)

Upvotes: 5

dominik
dominik

Reputation: 5935

I think the issue is that wasm-clingo exports the module itself but import { Module } from 'wasm-clingo' expects a property.

Try

import Clingo_ from 'wasm-clingo';
const Clingo: typeof Clingo_ = (Clingo_ as any).default || Clingo_;

Upvotes: 0

Related Questions