Search code examples
typescriptemscriptenembind

How can I generate typescript types for an Emscripten project?


I don't want to write TypeScript type declaration files for my Emscripten project manually. Is there a way to get such type declaration files generated automatically? Ex. for variables, functions, classes, etc.


Solution

  • There's related discussion in this GitHub issue ticket: Using embind to generate TypeScript typings #7083.

    Some support was added to embind around version 3.1.43. Embind Docs are here.

    Embind supports generating TypeScript definition files from EMSCRIPTEN_BINDINGS blocks. To generate .d.ts files invoke emcc with the embind-emit-tsd <emcc-emit-tsd> option::

    emcc -lembind quick_example.cpp --emit-tsd interface.d.ts
    

    Running this command will build the program with an instrumented version of embind that is then run in node to generate the definition files. Not all of embind's features are currently supported, but many of the commonly used ones are. Examples of input and output can be seen in embind_tsgen.cpp and embind_tsgen.d.ts.

    Other related functionality is still pending at the time of this writing:

    Note: the flag was originally named --embind-emit-tsd, but in version 3.1.57, the name of the flag was changed to --emit-tsd.


    If you use emcmake / CMake, this goes in the target's link options. Ex.

    target_link_options(my_target_js PRIVATE
      --emit-tsd "$<TARGET_FILE_DIR:my_target_js>/my_target.d.ts" # or wherever else you want it to go
    )
    

    You may also want to subscribe to notifications on https://gitlab.kitware.com/cmake/cmake/-/issues/20745.


    There are also some Emscripten-external projects that others in the community have made, each with their own interfaces and some limitations: