1

I have a c addon(using napi)for nodejs,and i can run it correctly in js code.now i want to use it in typescript,i try to write a .d.ts file but always fail.how can i write a d.ts file correctly? The c addon is a helloworld code like this:

#include <node_api.h>
#include <stdio.h>


napi_value Helloworld(napi_env env, napi_callback_info info)
{
    napi_status status;

    size_t argc = 1;
    napi_value argv[1];
    status = napi_get_cb_info(env, info, &argc, argv, 0, 0);
    if(status != napi_ok )
    {
        napi_throw_type_error(env,"", "Wrong number of arguments");
        status = napi_get_undefined(env, argv);
    }
    printf("Hello\n");
    return NULL;
}

napi_value Init(napi_env env, napi_value exports)
{
    napi_status status;
    napi_property_descriptor des =
       { "helloworld", 0, Helloworld, 0, 0, 0, napi_default, 0 };
    status = napi_define_properties(env, exports, 1, &desc);
    return exports;
}

NAPI_MODULE(addon, Init)

and the js code is this:

//this can run
const addon = require("../1/build/Release/addon");
addon.helloworld();

js code can run.and now i want to do this in typescript, how can i write a .d.ts file and how can i run it in typescript?thanks. i have try some but fail:

//this is fail code    
declare module "addon" {
      function helloworld():string 
      export = addon
    }

    /*
    const addon = require('./addon')
    declare  module 'addon'{
      export function addon.helloworld():string 
    }
    export function addon.echo(input: string):string
    export function echo {
    } = addon.echo */
    /* export = helloworld
    declare function helloworld (): string
     */
    /*
    export = MyFunction;
    declare function MyFunction(): string;
    */

    /* const addon = require('./addon')
    export default module 'addon' {
      export function helloworld():string
    }  */
    /* 
    const addon = require('./addon')
    export function helloworld():string
     */
  • Possible duplicate of [Typescript declarations file for Node C++ Addon](https://stackoverflow.com/questions/44275172/typescript-declarations-file-for-node-c-addon) – ZachB Jun 11 '18 at 20:12

1 Answers1

4

Try to add a addon.d.ts file to the folder '../1/build/Release/', The content should be:

export function helloworld (): string

You can see this issue for more details: https://github.com/Microsoft/TypeScript/issues/8335

TomWan
  • 319
  • 2
  • 9