Typescript declarations file for Node C++ Addon

Viewed 4156

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?

4 Answers

If you need to do an ambient declaration, (as I did because I'm using Node-Gyp + Webpack), you can add a mymodule.d.ts:

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

    declare class Item extends SpaceItem {
        GetItemName(): number;
        CreateMesh(StepData, FormNote, RegDuplicate?);
    }

    var Enabler: {
        EnableMathModules(string, string);
    };
}

And then require this

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

Another way to do this is similiar to Nick Kallen's way.

You're basically using a naming trick. If you do:

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

When 'compiled' to javascript, it will see the file as hello.node. Typescript will see the file as its name + a typescript file extension.

So this is how your *.node directory should look:

-hello.node

-hello.node.d.ts

-if-windows-hello.dll

In my hello.node.d.ts file I have:

export const hello: () => string;
Related