Search code examples
typescriptwebassembly

How to import WebAssembly functions to TypeScript?


I have an existing project written in TypeScript and I'm trying to import a WebAssembly Module to replace some functionality.

I have managed to successfully import the WebAssembly module by extracting the logic for loading the .wasm to a .js file. This is it's own TypeScript module and is imported into the .ts file where I want to use the WebAssembly functions.

For demonstration purposes I have made a simple add function in wasm.

In the .ts that is compiled to .wasm with AssemblyScript:

export function add(a: i32, b: i32): i32 {
  return a + b;
}

In the .js file:

export async function loadWasm() {
  const imports = {}; // Omitted the contents since it's most likely irrelevant
  const module = await 
  WebAssembly.instantiateStreaming(fetch('path/to/file.wasm'),imports);
  return module;
}

And in the .ts file where I want to use the WebAssembly:

loadWasm().then((module: any) => {
  let addFunc: ((a: number, b: number) => any) = module.add;
  console.log('Adding 2 and 5 in Wasm: ' + addFunc(2, 5));
});

But when running this it gives me the following error:

Uncaught (in promise) TypeError: addFunc is not a function at eval

Does anyone know what causes this?


Solution

  • Try this snippet:

    loadWasm().then(module => {
      const { add: addFunc } = module.instance.exports;
      console.log(addFunc(2, 5));
    });