Node C++ Addon Typescript declaration file

I have developed a Node C++ Addon that wraps a class similar to the one outlined in the official Node documentation. By using require(), I am able to access my addon and retrieve the constructor for my class in order to instantiate it.

const { MyClass } = require('myaddon');
const obj = new MyClass('data');

My next goal is to replicate this process using TypeScript. However, I am struggling to find the correct combination of .d.ts file and import statement to achieve this. Ideally, I would like to define my class within the module and specify that it has a constructor that accepts a string parameter. This way, I could simply do:

import { MyClass } from 'myaddon';
const obj = new MyClass('data');

Has anyone come across any examples of how to accomplish this task?

Answer №1

After taking the advice of @ZachB, I have finally figured it out. I made a myaddon.ts file that contains the following:

const myaddon = require('./build/release/myaddon')

export interface MyClass {
    myMethod(arg: string): number
}

export var MyClass: {
    new(param: string): MyClass
} = myaddon.MyClass

Now you can utilize it like this:

import { MyClass } from 'myaddon'

const thing: MyClass = new MyClass('something')
const answer: number = thing.myMethod('blah')

Answer №2

While there may be alternative approaches, I personally implement the following approach:

// bindings.ts
// Define the interface for my addon:
export interface MyBindings {
    myMethod1: (arg1: number) => null;
}
// Require and load it
var myClass: MyBindings = require("./build/release/myaddon");
export default myClass;

Subsequently, I access it from different sections of my module using

import bindings from "../bindings"
.

Answer №3

If you find yourself in need of making an ambient declaration (like I did when working with Node-Gyp + Webpack), you can create a file named mymodule.d.ts:

declare module "*mymodule.node" {
    declare class SpaceObject {}

    declare class Object extends SpaceObject {
        getObjectName(): number;
        createMesh(data, notes, duplicate?);
    }

    var Enabler: {
        enableModules(moduleName: string, version: string);
    };
}

After that, you can import it like this:

import myModule from '../build/Release/mymodule.node';

Answer №4

Inspired by Nick Kallen's approach, here is another method to achieve the same result.

By utilizing a naming technique, you can specify the file extension in Typescript:

import test = require("../test/build/Release/hello.node");

After compilation to JavaScript, the file will be recognized as hello.node. However, Typescript will identify it by its name along with a .d.ts extension.

Your *.node directory structure should include:

-hello.node

-hello.node.d.ts

-if-windows-hello.dll

Within my hello.node.d.ts file, the content is as follows:

export const hello: () => string;

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

I'm sorry, we couldn't locate the module: Unable to find the path '../types/index'

After spending an hour attempting to troubleshoot this issue, I am still unable to find a solution. I have stored index.d.ts in the types folder. The content of the types file is as follows: export interface tag { created_at: string id: nu ...

A Typescript type that verifies whether a provided key, when used in an object, resolves to an array

I have a theoretical question regarding creating an input type that checks if a specific enum key, when passed as a key to an object, resolves to an array. Allow me to illustrate this with an example: enum FormKeys { x = "x", y = "y&q ...

Tips for defining a function across a Angular project

I have the following configuration set up in an Angular5 project using Angular-cli 1.5 within typings.d.ts declare interface String { toSentenceCase(): string; } declare function _debug(o, message?, type?): void; inside app/core/common.ts String.pro ...

Passing a FormGroup from an Angular 2 component as a parameter

I have a FormGroup that contains a SubFormGroup: sub formGroup initialize: this.fg=new FormGroup({ name: new FormControl(), abcFg: new FormGroup({ aaa: new FormControl(), bbb: new FormControl() }) }) ...

What is the process of playing blob videos (avi, mov) in Angular14?

I've been struggling with this issue for quite some time without knowing how to resolve it. After some research, I came across a similar question: how to play blob video in angular. However, the problem is that the demo provided in the answer does no ...

Instructions on invoking a function when a button is clicked

I am attempting to trigger a dataUpdate function upon clicking the edit() button I am striving to modify the record Current Version: Angular CLI: 10.0.6 Angular: 10.0.10 registration.component.html <div> <button type="button&quo ...

The name 'CallSite' is missing from the Error stack trace when working with Node.js and TypeScript

I am facing an issue with the following code: Error.prepareStackTrace = function ( error: Error, stack: Array<CallSite>, ) { return self.parse(fiber, error, stack) } I am attempting to import the CallSite, but it seems like it cannot be found ...

The 'ObjectID' property is not present in the 'CollectionStatic' data type

Encountering an issue with the MongoDB npm module: mongoId = new Mongo.Collection.ObjectID()._str; Attached is a screenshot for reference. Appreciate any assistance. ...

Problem with Typescript: The type '{ x;y }' is required to have a '[Symbol.iterator]()' method

Just starting out with Typescript and tackling the task of converting a React project from JavaScript to TypeScript. I've been diving into various posts for guidance, but I feel like I'm going in circles. Any assistance would be greatly appreci ...

Obtaining the count of a specific column in Angular 6 by grouping objects based on the same value in an array

In TypeScript, I have an array of objects and I am using a foreach loop. The array contains 2 columns with a progress value of 100, while the rest have values less than 100. My goal is to calculate the count of columns with a progress value of 100, which ...

A guide on including a class to a DOM element in Angular 6 without relying on Jquery

Currently, I have created a component template using Bootstrap that looks like this: <div class="container"> <div class="row my-4"> <div class="col-md-12 d-flex justify-content-center"> <h2> ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

Issue with Angular 4: Radio button defaults not being set

After hardcoding the value in component.ts, I am able to see the pre-selected radio button. However, when attempting to retrieve the value from sessionStorage, it does not work as expected. The value is visible in the console though. Could someone please ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

Use TypeScript to cast the retrieved object from the local storage

const [savedHistory, setSavedHistory] = useState(localStorage.getItem('history') || {}); I'm facing an issue in TypeScript where it doesn't recognize the type of 'history' once I fetch it from localStorage. How can I reassign ...

Expressjs - Error: Headers already sent to the client and cannot be set

After testing various solutions from others, I am still unable to resolve this error. My objective is to iterate through each item in the array sourced below: novel.ts export let indexList = (req: Request, res: Response) => { novel.getAllDocuments ...

Angular 6: Harnessing the Power of RouterLinks

Can you navigate to a different section of another page using the defined ID without having to reload the entire page? ...

How to Retrieve a Symbol in TypeScript

In the code snippet below, there is a function named factory that returns a Symbol of type Bob. However, TypeScript appears to forget the type of the return value immediately, leading to an error when trying to assign the return value to variable test one ...

Exploring ways to retrieve checkbox values instead of boolean values upon submission in Angular

I am currently working with a template-driven form and facing an issue. Despite receiving true or false values, I actually need to retrieve the value of checkboxes. <form #f = "ngForm" (ngSubmit) = "onClickSubmit(f.value)"> ...

Issue encountered while using Typescript with mocha: Unable to utilize import statement outside a module

Exploring the world of unit testing with mocha and trying to create a basic test. Project Structure node_modules package.json package-lock.json testA.ts testA.spec.ts tsconfig.json tsconfig.json { "compilerOptions": { "target&qu ...