typego

module
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 22, 2026 License: MIT

README

TypeGo

typego is an embedded TypeScript runtime for Go. It lets you script Go applications with TS without the overhead of Node.js or the boilerplate of manual FFI bindings.

Getting StartedFeaturesExamplesOptimizationContributingLicense

[!NOTE] Project Status: TypeGo is under active development. However, please note that maintenance is limited as I am balancing this project with my university commitments. Issues and PRs are welcome but may see delayed responses.

Unlike typical runtimes that communicate over IPC or JSON-RPC, typego runs a JS engine (Sobek) directly inside your Go process. You can import Go packages as if they were native TS modules using the go: prefix, allowing for zero-copy data sharing and direct access to Go’s standard library.

Features

  • Direct Go Integration: Import any Go package as a native TS module (go:fmt, go:github.com/gin-gonic/gin).
  • Standard Library Intrinsics: Direct access to Go-native keywords and types like go routines, makeChan, select, defer, ref/deref, and make/cap.
  • Smarter Type Linker: Automatic, recursive type generation for Go structs, interfaces, and methods. Supports struct embedding (extends) and nested type resolution.
  • True Parallelism: Goroutine-based workers with zero-copy shared memory (typego:memory).
  • Modern Package Ecosystem: Built-in CLI for managing Go dependencies with typego.modules.json and typego.lock.
  • Fast Developer Loop: Hot-reloading dev server and ~0.2s interpreter startup. Compiles to single-binary with --compile.

Tech Stack

  • Language: Go 1.21+, TypeScript
  • JS Engine: Sobek (fork of Goja, pure Go)
  • Bundler: esbuild
  • CLI: Cobra

Getting Started

Installation
go install github.com/repyh/typego/cmd/typego@latest
Quick Start
typego init myapp
cd myapp
typego run src/index.ts

Standard Library Intrinsics

TypeGo provides first-class support for Go-native keywords and low-level primitives as global functions.

Function Type Description
go(fn, ...args) Concurrency Launches a background goroutine.
makeChan<T>(size?) Concurrency Creates a synchronized Go channel.
select(cases) Concurrency Multiplexes channel operations (send/receive/default).
ref(val) Memory Creates a pointer handle (Ref<T>) to a value on the Go heap.
deref(ptr) Memory Dereferences a pointer or Ref object.
make(Type, len, cap?) Memory Allocates high-performance slices (TypedArrays).
cap(v) Memory Returns the capacity of a slice or buffer.
copy(dst, src) Memory Performs high-speed memory copying between buffers.
sizeof(obj) Memory Estimates the memory footprint of a JS/Go object.
defer(fn) Control Registers a function to run when the current typego.scope exits.
panic(err) Control Triggers a native Go panic.
recover() Control Recovers from a panic inside a defer block.
iota Constant Auto-incrementing compile-time constant.

Project Structure

A standard TypeGo project consists of the following structure:

  • src/: Directory for your TypeScript source files.
  • typego.modules.json: Dependency manifest for Go packages.
  • typego.lock: [New] Auto-generated lockfile for reproducible Go module versions.
  • .typego/: [Internal] Managed workspace for build artifacts and cached TypeScript types (go.d.ts).
  • package.json: Standard Node.js manifest for NPM dependencies (handled via esbuild).
Commands
Command Description
typego run <file> Execute TypeScript (fast interpreter mode)
typego dev <file> Development server with hot-reload
typego build <file> Build standalone executable
typego init [name] Scaffold new project (--npm for Node interop)
typego types Generate .d.ts for Go imports
typego add <pkg> Add a Go module dependency
typego remove <pkg> Remove a Go module dependency
typego list List configured Go dependencies
typego update Update Go modules to latest versions
typego outdated Check for newer Go module versions
typego install Manually trigger JIT build/dependency resolution
typego clean Reset build cache and temporary workspace
Package Management

TypeGo uses a typego.modules.json file to manage Go dependencies. This allows you to use any Go package in your TypeScript code.

# Add a Go package. Ecosystem will automatically resolve versions and sync types.
typego add github.com/gin-gonic/gin
// src/index.ts
import { Default } from "go:github.com/gin-gonic/gin";

const app = Default();
app.GET("/ping", (c) => c.JSON(200, { message: "pong" }));
app.Run();

TypeGo automatically manages a .typego/ workspace, handling go mod tidy, JIT compilation, and TypeScript definition syncing behind the scenes.

Examples

Go Imports
import { Println, Printf } from "go:fmt";
import { Sleep } from "go:sync";

Println("Hello from Go!");
await Sleep(1000);
Printf("Done after %dms\n", 1000);
Workers & Shared Memory
import { makeShared } from "typego:memory";
import { Worker } from "typego:worker";

const shared = makeShared("buffer", 1024);
const worker = new Worker("worker.ts");
worker.postMessage({ buffer: shared });
Concurrency
import { Spawn, Sleep } from "go:sync";

Spawn(async () => {
  for (let i = 0; i < 5; i++) {
    await Sleep(500);
    console.log(`Heartbeat ${i}`);
  }
});
Intrinsics

A short example demonstrating channels, select, and pointer handles (ref/deref).

import { Println } from "go:fmt";

// Channels + select
const ch = makeChan<number>(1);

go(() => {
  ch.send(42);
});

select([
  { chan: ch, recv: (v) => Println("received:", v) },
  { default: () => Println("no message") }
]);

// Pointer handles
const r = ref(100);
Println("before:", deref(r)); // 100
r.value = 200;
Println("after:", deref(r)); // 200

// TypedArray helpers
const buf = make(Uint8Array, 4);
Println("capacity:", cap(buf));

Applications

Field Can Do Cannot Do
Networking HTTP/WebSocket/TCP servers, proxies Kernel networking, eBPF
Backend REST APIs, microservices, job queues Native DB drivers (no CGO)
CLI Tools Build tools, code generators, automation Native GUI
Data Processing JSON/CSV, log aggregation, parallel ETL GPU acceleration
DevOps Health checks, log shippers, K8s clients Container runtimes
Real-Time Chat servers, game servers, notifications Hard real-time

Limitations

Limitation Impact
No JIT compilation ~10x slower raw JS than V8-based runtimes
No Web APIs No DOM, fetch, localStorage
No CGO Can't call C libraries
Explicit shared memory Must use makeShared()

When to Use

✅ Good Fit ❌ Use Alternatives
Backend needing true parallelism Browser/frontend apps
CLI tools with single binary Data science (use Python)
TypeScript team wanting Go perf Systems programming (use Rust/Go)
Serverless/edge (small binary) Mobile apps

Performance

TypeGo is optimized for high-throughput I/O and true parallelism. For a detailed breakdown of the execution model, interop overhead, and optimization strategies, see OPTIMIZATION.md.

Runtime Comparison

Feature TypeGo Node.js Deno Bun
TypeScript native ⚠️
True parallelism
Single binary
Shared memory ⚠️ ⚠️ ⚠️
NPM ecosystem ⚠️ ⚠️

Development

Prerequisites
  • Go 1.21+
  • Node.js 18+ (for NPM packages)
Building from Source
git clone https://github.com/repyh/typego.git
cd typego
go build -o typego.exe ./cmd/typego
Running Examples
./typego run examples/01-hello-world.ts
./typego run examples/02-go-concurrency.ts
./typego run examples/10-typego-stdlib.ts

License

MIT

Directories

Path Synopsis
Package bridge provides the JavaScript-to-Go binding layer for the TypeGo runtime.
Package bridge provides the JavaScript-to-Go binding layer for the TypeGo runtime.
core
Package core provides internal utilities for the TypeGo bridge layer.
Package core provides internal utilities for the TypeGo bridge layer.
modules/crypto
Package crypto provides bindings for Go's crypto packages.
Package crypto provides bindings for Go's crypto packages.
modules/fmt
Package fmt provides bindings for Go's fmt package.
Package fmt provides bindings for Go's fmt package.
modules/json
Package json provides bindings for Go's encoding/json package.
Package json provides bindings for Go's encoding/json package.
modules/net
Package http provides bindings for Go's net/http package.
Package http provides bindings for Go's net/http package.
modules/os
Package os provides bindings for Go's os package.
Package os provides bindings for Go's os package.
modules/sync
Package sync provides bindings for Go's sync package and concurrency primitives.
Package sync provides bindings for Go's sync package and concurrency primitives.
stdlib/memory
Package memory provides the typego:memory module for shared memory and stats.
Package memory provides the typego:memory module for shared memory and stats.
stdlib/worker
Package worker provides the typego:worker module for multi-threading.
Package worker provides the typego:worker module for multi-threading.
cmd
typego command
Package compiler provides TypeScript-to-JavaScript transpilation for TypeGo.
Package compiler provides TypeScript-to-JavaScript transpilation for TypeGo.
Package engine provides the core JavaScript execution environment for TypeGo.
Package engine provides the core JavaScript execution environment for TypeGo.
Package eventloop provides a thread-safe event loop for JavaScript execution.
Package eventloop provides a thread-safe event loop for JavaScript execution.
internal
builder
Package builder provides shared compilation pipeline components for the TypeGo CLI.
Package builder provides shared compilation pipeline components for the TypeGo CLI.
linker
Package linker provides dynamic Go package binding for TypeGo.
Package linker provides dynamic Go package binding for TypeGo.
pkg
cli
cli/cmd
Package cmd contains core TypeGo CLI commands.
Package cmd contains core TypeGo CLI commands.
cli/internal
Package internal provides shared CLI utilities for consistent output and interaction.
Package internal provides shared CLI utilities for consistent output and interaction.
cli/pkg
Package pkg contains all package manager related CLI commands.
Package pkg contains all package manager related CLI commands.
tests

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL