How to compile typescript code along with C++?

1.5k Views Asked by At

I have a project which is completely in C++. Also I have one more file which is in typescript ( I wasn't able to find libraries equilvelent in C++). The typescript file is doing the following: 1 It has typescript CLI code kinda of generator that will generate some functions in respective files.

My compiler is gcc.

Can please someone tell me .. is it possible to link and compile it ? Is yes..How ?

3

There are 3 best solutions below

0
Dimava On

tl;dr provide a node executable and use spawn a node myfile.js from your program


  1. You (generally) can't compile typescript into bytecode, it will always be a .JS text file executed with #!/usr/bin/env node

  2. If you want to run JS from C++, the easiest way is to exec or spawn node process

  3. If you want to run C++ from JS, the easiest way is to exec or spawn c++ process, but if you want to dig into that look for how to make bindings for node https://nodejs.org/api/addons.html

0
lorro On

A relatively easy way to bridge C++ and JS/TS is node-addon-api. There's a simplified API for this, inline-cpp, which I have a branch for:

Example JS (same with TS):

const hello = InlineCPP `
  String func(const CallbackInfo& info) {
    return String::New(info.Env(), "Hello world!");
  }
`
console.log(hello()); // Hello world!
0
chrispepper1989 On

So the above two answers are arguably the best choices for your problem.

But you did say "compile" and there are compiled solutions.

In your case it sounds like you have TS "code" (rather then a library) that you want as C++ in which case https://github.com/ASDAlexander77/TypeScript2Cxx

Might be an answer.

Alternatively you could go completely the other way and compile your C++ code to JS using

Emscripten

For your specific case I wouldn't actually recommend either and instead as @dimava put I'd go with the spawned node process in ur C++ program (essentially your code should shell "npx TS_CODE input" and process the output) :)