What is the process for importing WebAssembly functions into TypeScript?

I currently have a TypeScript project and am in the process of incorporating a WebAssembly Module to replace certain functionalities.

Successfully importing the WebAssembly module involved moving the .wasm loading logic to its own .js file, which is then imported as a TypeScript module into the file where I intend to use the WebAssembly functions.

As an example, I created a basic add function in WebAssembly:

In the .ts that compiles to .wasm using AssemblyScript:

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

In the .js file:

export async function loadWasm() {
  const imports = {}; // Omitted for simplicity
  const module = await 
  WebAssembly.instantiateStreaming(fetch('path/to/file.wasm'),imports);
  return module;
}

And in the .ts file where I want to utilize 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));
});

However, upon execution, I encounter the following error:

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

Would appreciate any insights on what could be causing this issue.

Answer №1

Give this code a shot:

initiateWasm().then(mod => {
  const { multiply: multFunc } = mod.instance.exports;
  console.log(multFunc(3, 6));
});

Answer №2

Here's a convenient way to utilize AssemblyScript Loader directly within TypeScript:

This method necessitates the inclusion of "regenerator-runtime": "^0.13.2", which can be imported alongside the loader in the .ts file where you intend to implement the Wasm module:

import { instantiateStreaming, ASUtil } from 'assemblyscript/lib/loader';
import { regeneratorRuntime } from 'regenerator-runtime';

The instantiation process is as follows:

interface MyApi {
    add(a: number, b: number): number;
}

async function loadWasm(): Promise<ASUtil & MyApi> {
    const imports: any = {};
    let module: ASUtil & MyApi = await instantiateStreaming<MyApi>(fetch('path/to/file.wasm'), imports);
    return module;
}

Following this, implementation becomes straightforward:

loadWasm().then((module) => {
    console.log('The result is: ', module.add(3, 4));
});

In addition, you have access to various other functionalities provided by the Loader:

let str = "Greetings Earth!";
let reference = module.__retain(module.__allocString(str));
console.log(module.__getString(reference));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The identifier 'id' is not recognized within the 'never' type in Angular

Hello there, I am currently working on a small project for a store website. You can find the project here. However, I have encountered an issue when trying to move items to the cart. Specifically, in the source code file app/components/product-list/produc ...

What is the reason behind the lack of covariance in an interface when using a type of T[keyof T]?

I'm attempting to enable type covariance so that Type<Cat> can be treated as a Type<Animal>, for instance, treating a list of Cats as a list of Animals. However, using the type T[keyof T] in a method within the Type interface seems to hind ...

Setting the TypeScript version while initializing CDK

When creating a new CDK app in typescript, I typically use the following command: npx --yes <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9babdb299e8f7e8eae1f7eb">[email protected]</a> init app --language typesc ...

Guide for transferring data from HTML to controller in Angular 4

Hello everyone, I am new to Angular and currently working on displaying a table based on the value of a toggle button. I have implemented a toggle button using Angular material, but I'm struggling to pass the data to my controller. I would really app ...

How can I provide type annotations for search parameters in Next.js 13?

Within my Next.js 13 project, I've implemented a login form structure as outlined below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { signIn } from "n ...

The functionality of d3 transition is currently non-existent

I've encountered an issue with my D3 code. const hexagon = this.hexagonSVG.append('path') .attr('id', 'active') .attr('d', lineGenerator(<any>hexagonData)) .attr('stroke', 'url(#gradi ...

The custom component is not updating the NgIf directive in HTML even though it receives a boolean variable

I am struggling with a custom component that includes an *ngIf in its view to handle a boolean variable, but for some reason the *ngIf directive is not working. Here is the code snippet: Component @Input('title') titleText; @Input('backButt ...

What is the best way to organize an Angular library for multiple import paths similar to @angular/material, and what advantages does this approach offer?

When importing different modules from @angular/material, each module is imported from a unique package path, following the format of @organization/library/<module>. For example: import { MatSidenavModule } from '@angular/material/sidenav'; ...

Is there a way to incorporate new members into a pre-existing type in TypeScript?

While examining the definition file for the commander project, one can observe the following interface being utilized: interface IExportedCommand extends ICommand { Command: commander.ICommandStatic; Option: commander.IOptionStatic; [key: stri ...

Tips for accurately documenting the Props parameter in a React component with Destructuring assignment

Attempting to create JSDocs for a React component using destructuring assignment to access props: const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... } The issue arises when trying to document multiple parameters in JSDocs ...

Ways to resolve the issue of incompatible parameters 'action' types in JavaScript

I'm encountering a common problem, but I can't figure out why this error is happening. After updating redux, I encountered the following error message: TS2322: Type '(state: ILanguage | undefined, action: PayloadAction<ILanguage>) =&g ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

Get the file without specifying type in request - Angular

Is it possible to download a file solely through the response without specifying a responsetype in the header? I am looking for a way to download the file without including any additional parameters in the header. ...

When using Vue 3 in my app, I discovered that all the TypeScript files are easily accessible through the browser console

I recently completed my Vue3 js app with Typescript, and I have noticed that all the Typescript files are easily accessible for anyone to view through the Sources tab of the browser console. The code is perfectly clear and readable. Is there a method to p ...

Error: Promises must be managed correctly

I've been working on a timer-based function that is supposed to run once a week and create almost identical copies of existing documents. However, every time I try to execute it, I encounter the error message "Promises must be handled appropriately." ...

Neglecting the error message for type assignment in the Typescript compiler

Presented here is a scenario I am facing: const customer = new Customer(); let customerViewModel = new CustomerLayoutViewModel(); customerViewModel = customer; Despite both Customer and CustomerLayoutViewModel being identical at the moment, there is no ...

Encountering a Typescript error with Next-Auth providers

I've been struggling to integrate Next-Auth with Typescript and an OAuth provider like Auth0. Despite following the documentation, I encountered a problem that persists even after watching numerous tutorials and mimicking their steps verbatim. Below i ...

How can I postpone the initialization of ngOnInit in Angular 7?

While attempting to send and retrieve data for display, I encountered an issue where the component initializes before the new data is added to the server. This results in a missing element being displayed. Is there a way to delay the initialization proce ...

Creating a service in AngularJS 1.8 with ES6 modules that acts as a bridge to a class based API interface

As I continue to enhance a codebase that originally consisted of a mix of different versions of AngularJs and some unstructured code utilizing various versions of a software API, I encounter an interesting quirk. It appears that this API is accessible thro ...

The Vue data retrieved from an API using onMounted() is not initially showing up in the DOM. However, it magically appears after I make changes to the template

Hello and thank you to those taking the time to read this. I am new to Vue, so I may be overlooking something obvious here, but after being stuck for several days, I am reaching out for help. In my SFC file, I have an onMounted function fetching data from ...