Typescript declarations file for Node C++ Addon

2019-06-24 08:07发布

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?

2条回答
萌系小妹纸
2楼-- · 2019-06-24 08:51

There are perhaps better ways of doing this, but I use the following pattern:

// bindings.ts
// Declare the interface of your addon:
export interface MyBindings {
    myMethod1: (arg1: number) => null;
}
// Load it with require
var myClass: MyBindings = require("./build/release/myaddon");
export default myClass;

And then use it from other parts of my module with import bindings from "../bindings".

查看更多
可以哭但决不认输i
3楼-- · 2019-06-24 08:54

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')
查看更多
登录 后发表回答