Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript declarations file for Node C++ Addon

I have a Node C++ Addon that provides a wrapped class similar to the one in the Node documentation. I can require() my addon and then get the constructor for my class to create an instance.

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

Now I want to use TypeScript to do the same. I can't find the right combination of .d.ts file and import statement to make this work. I guess ideally I'd like to declare my class is in the module and has a constructor that takes a string. I could then just do:

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

Any examples of this that people have seen?

like image 324
Doug Schaefer Avatar asked May 31 '17 03:05

Doug Schaefer


People also ask

What is declare module in TypeScript?

The TypeScript declares module is one of the modules and keyword it is used for to surround and define the classes, interfaces; variables are also declared it will not originate with the TypeScript like that module is the set of files that contains values, classes, functions/methods, keywords, enum all these contains ...

What is ESM in TypeScript?

ESM is an important step in the JavaScript ecosystem because it allows static analysis of the dependency tree. For bundlers such as Webpack, this is huge as it allows the compiled bundle only to contain code that is required at runtime, which means a smaller download size when loading code over the network.

What is a node addon?

Node. js Addons are dynamically linked shared objects, written in C++. It can be loaded into Node. js using the require() function and also used just as if they were an ordinary Node. js module.

Why do we need C++ addons in node JS?

Node technology was written on C++ under the hood which is very fast and powerful in development of applications for low level tasks or heavy computations. As a result, Node is C++ friendly and allows developers to run C++ code in Node. js applications. This is done with the help of Node addons.


1 Answers

I think I finally have it. As suggested by @ZachB, I created a myaddon.ts file that has the following:

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

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

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

Then use it:

import { MyClass } from 'myaddon'

const thing: MyClass = new MyClass('something')
const answer: number = thing.myMethod('blah')
like image 193
Doug Schaefer Avatar answered Sep 20 '22 18:09

Doug Schaefer