TypeScript as Glue: Integration with Python, C++, and Go

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why Doesn't TypeScript Live in a Vacuum?

\n

When we write in TypeScript, we get used to its strictness, autocompletion, and generics. But sooner or later, every developer faces the question: "What if I need to call code in Python, C++, or Go?". Surely we don't have to rewrite the entire project?

\n

The good news: TypeScript is not an isolated island. It can be friends with other languages through native modules, WebAssembly, gRPC, and even regular HTTP bridges. In this article, we'll break down three real-world scenarios for integrating TypeScript with other languages. You'll learn how to glue together the frontend, backend, and high-performance computing in one stack.

\n\n

Scenario 1: TypeScript + Python — Data Science on Steroids

\n

Python is the king of machine learning and data analysis. But its weakness is web interfaces. TypeScript, on the other hand, works brilliantly in the browser and on the server. It makes sense to combine their strengths.

\n\n

Method A: HTTP Microservice (Simplest)

\n

The most obvious path is to run a Python server (e.g., FastAPI) and call it from TypeScript via fetch.

\n

Python (backend.py):

\n
from fastapi import FastAPI\nfrom pydantic import BaseModel\nimport joblib\n\napp = FastAPI()\nmodel = joblib.load('model.pkl')\n\nclass InputData(BaseModel):\n    features: list[float]\n\n@app.post("/predict")\ndef predict(data: InputData):\n    result = model.predict([data.features])\n    return {"prediction": result.tolist()}\n
\n

TypeScript (frontend.ts):

\n
interface PredictionResponse {\n    prediction: number[];\n}\n\nasync function getPrediction(features: number[]): Promise<number[]> {\n    const response = await fetch('http://localhost:8000/predict', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify({ features })\n    });\n    \n    if (!response.ok) throw new Error('Prediction error');\n    \n    const data: PredictionResponse = await response.json();\n    return data.prediction;\n}\n\n// Usage\ngetPrediction([1.2, 3.4, 5.6])\n    .then(pred => console.log('Result:', pred))\n    .catch(err => console.error(err));\n
\n\n

Method B: Python Scripts via child_process (for Backend)

\n

If you don't need a separate server, you can run Python directly from Node.js. This is convenient for one-off tasks — image processing, report generation.

\n
import { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execPromise = promisify(exec);\n\nasync function runPythonScript(scriptPath: string, args: string[]): Promise<string> {\n    const command = `python3 ${scriptPath} ${args.join(' ')}`;\n    const { stdout, stderr } = await execPromise(command);\n    \n    if (stderr) throw new Error(`Python error: ${stderr}`);\n    return stdout.trim();\n}\n\n// Example: pass JSON to Python\nconst result = await runPythonScript('./analyze.py', ['--data', '{"value": 42}']);\nconsole.log('Python replied:', result);\n
\n

Important: this approach is slower than a microservice, but doesn't require setting up a separate server. Suitable for prototypes and CI/CD.

\n\n

Scenario 2: TypeScript + C++ — Blazing Speed

\n

When you need to process video, audio, or cryptography, Python might not be enough. This is where C++ and its powerful ally — WebAssembly (WASM) — come into play.

\n\n

Compiling C++ to WASM and Calling from TypeScript

\n

Suppose we have a simple C++ function that accelerates matrix multiplication:

\n
// matrix.cpp\nextern "C" {\n    void multiply_matrices(float* a, float* b, float* result, int size) {\n        for (int i = 0; i < size; i++) {\n            for (int j = 0; j < size; j++) {\n                float sum = 0.0f;\n                for (int k = 0; k < size; k++) {\n                    sum += a[i * size + k] * b[k * size + j];\n                

Blogs

Book Recommendations