r/typescript • • 17d ago

libtmux-ts 0.1 - TypeScript Client for tmux

Thumbnail
github.com
1 Upvotes

I maintain libtmux, the Python library that's been around since 2016, and am porting it to more languages. This is the TypeScript / Node.js port. In many ways, this is more capable than the current Python implementation.

One of the main ways it differs is keeping immutable snapshots and typed querying of the tmux object graph (Server, Session, Window, Pane). It also supports tmux's control mode and batching of operations. Architecturally, libtmux for Python would have to break its API to adopt this snapshot model. For other libtmux ports, they don't have the encumbrance of worrying about API breakages to downstream users.

A word on AI: This project is experimental, and I used LLMs extensively to build it (with zero runtime dependencies and automated tests against live tmux(1) servers). I keep libtmux's AI policy at https://libtmux.org/en/meta/ai-policy/ based on Pallets', tmux's, and Java's.

There are four npm packages:

PackageWhat it doesSource
libtmuxSessions, windows, panes, queries and eventsGitHub
@libtmux/mcpMCP serverGitHub
@libtmux/workspaceBuild sessions from configuration objectsGitHub
@libtmux/workspace-cliLoad and capture YAML / JSON workspacesGitHub

The core also exports libtmux/selection, libtmux/engine and libtmux/testing. Those come with libtmux; there's nothing extra to install.

libtmux core: typed Node.js library for tmux

npm · GitHub · Homepage · Guides · API Explorer

What's interesting:

The installation commands use Node 22+ with npm and need tmux 3.3a+ installed locally. Save the examples as .mts files; they also run with Bun. The Node commands use tsx.

Install:

npm install libtmux

Save as demo.mts. It creates a separate tmux server, adds two windows, splits the editor window and names a pane using its title. It cleans up that server afterward.

The queries match a session name, window names and a pane title, with OR, a string prefix and relationships.

import { Server } from "libtmux";

const server = new Server({
  socketName: `libtmux-demo-${process.pid}`,
  configFile: "/dev/null",
});

const session = await server.newSession({ name: "demo" });

try {
  const [editor] = await server.batch([
    session.plan.newWindow({ name: "editor" }),
    session.plan.newWindow({ name: "logs" }),
  ]);
  const build = await editor.split({ shellCommand: "cat" });
  await build.setTitle("build");

  const snapshot = await server.snapshot();
  const matchedSession = snapshot.sessions.where({ name: "demo" }).one();
  const matches = snapshot.windows.where({
    session: { is: { name: "demo" } },
    OR: [
      { name: { startsWith: "edit" } },
      { name: "logs" },
    ],
    panes: { some: { active: true } },
  });

  const matchedPane = snapshot.panes.where({
    title: "build",
    session: { is: { name: "demo" } },
    window: { is: { name: "editor" } },
  }).one();

  console.log(`session: ${matchedSession.name}`);
  for (const window of matches) {
    console.log(`${window.name}: ${window.panes.length} panes`);
  }
  console.log(`pane: ${matchedPane.title}`);
} finally {
  await server.kill();
}

For Node, install tsx:

npm install --save-dev tsx

Run with Node:

node --import tsx demo.mts

Or Bun:

bun demo.mts

Or use the tsx command:

npx tsx demo.mts

Each prints:

session: demo
editor: 2 panes
logs: 1 panes
pane: build

P.S. Try changing the pane's window condition from "editor" to "editor2". .one() raises a NoMatchError carrying the query that failed. Even in the alpha, the library means to raise detailed, typed errors.

The error includes the query:

  code: 'NoMatchError',
  subcommand: undefined,
  query: {
    pane_title: 'build',
    session: { is: { name: 'demo' } },
    window: { is: { name: 'editor2' } }
  }

Planning operations, then querying the result

The earlier example uses session.plan to describe work, and server.batch to run it. Each creation normally reads a snapshot back; a batch shares that last read (example).

Save as batch.mts. This counts invocations through recordInvocations, creates the same three windows each way, then chains queries over one snapshot.

import { Server } from "libtmux";
import { recordInvocations } from "libtmux/testing";

const recorder = recordInvocations();
const count = () => recorder.recording().invocations.length;
const server = new Server({
  socketName: `libtmux-batch-${process.pid}`,
  configFile: "/dev/null",
  engine: recorder.engine,
});

try {
  const serial = await server.newSession({ name: "serial" });
  const session = await server.newSession({ name: "demo" });
  const names = ["editor", "logs", "shell"];

  let before = count();
  for (const name of names) {
    await serial.newWindow({ name });
  }
  console.log(`sequential: ${count() - before} invocations`);

  before = count();
  const [, logs] = await server.batch(
    names.map((name) => session.plan.newWindow({ name })),
  );
  console.log(`batch: ${count() - before} invocations`);
  await logs.panes.one().setTitle("build");

  const snapshot = await server.snapshot();
  before = count();
  const pane = snapshot.panes
    .where({ session: { is: { name: "demo" } } })
    .where({ window: { is: { name: "logs" } } })
    .where({ title: { startsWith: "bui" } })
    .one();
  if (!pane.session || !pane.window) throw new Error("pane relationships are missing");
  console.log(`${pane.session.name} / ${pane.window.name} / ${pane.title}`);
  console.log(`queries: ${count() - before} invocations`);
} finally {
  await server.kill();
}

node --import tsx batch.mts

sequential: 6 invocations
batch: 4 invocations
demo / logs / build
queries: 0 invocations

Or Bun:

bun batch.mts

Or tsx:

npx tsx batch.mts

The counts cover those window creations, after setup. The queries run in memory; take another snapshot when you want fresh tmux state. A batch runs its commands in order and stops on failure, leaving earlier changes applied.

Control mode: wait for pane output

Server.connect keeps a control observer open. subscribe gives you the events, while commands still use the server's normal executor (agent example).

Save as control.mts. Here we listen before sending the command, then capture what ended up in the pane. The printf arguments keep the completed line out of the echoed command.

import { Server } from "libtmux";

const server = new Server({
  socketName: `libtmux-control-${process.pid}`,
  configFile: "/dev/null",
});

try {
  const session = await server.newSession({
    name: "demo",
    windowName: "editor",
    shellCommand: "sh",
  });
  const live = await server.connect({ target: session.id });
  try {
    const pane = (await live.snapshot()).panes.one();
    await pane.setTitle("build");
    let output = "";
    const printed = live.subscribe().find((event) => {
      if (event.kind !== "output" || event.paneId !== pane.id) return false;
      output += event.data;
      return output.includes("build: complete");
    }, { timeoutMs: 5_000 });

    await pane.sendKeys("printf 'build: %s\\n' complete");
    if ((await printed) === undefined) throw new Error("build output never arrived");
    console.log("event: build: complete");

    const line = (await pane.capture()).find((line) => line === "build: complete");
    if (line === undefined) throw new Error("build output missing from capture");
    console.log(`capture: ${line}`);
  } finally {
    await live.close();
  }
} finally {
  await server.kill();
}

node --import tsx control.mts

event: build: complete
capture: build: complete

Or Bun:

bun control.mts

Or tsx:

npx tsx control.mts

For waiting on a change to the session itself, live.waitFor accepts a snapshot predicate. The waitFor example waits for a list of windows to exist.

Testing your own code

libtmux/testing can also replay recorded calls. Save as replay.mts. This records a snapshot, stops the tmux server, then reads it back from the recording.

import { Server } from "libtmux";
import { recordInvocations, replayInvocations } from "libtmux/testing";

const socketName = `libtmux-record-${process.pid}`;
const server = new Server({ socketName, configFile: "/dev/null" });
const recorder = recordInvocations();

try {
  await server.newSession({ name: "demo" });
  const recording = new Server({ socketName, engine: recorder.engine });
  await recording.snapshot();
} finally {
  await server.kill();
}

const replayed = new Server({ engine: replayInvocations(recorder.recording()) });
const snapshot = await replayed.snapshot();
console.log(`replayed: ${snapshot.sessions.one({ name: "demo" }).name}`);

node --import tsx replay.mts

replayed: demo

Or Bun:

bun replay.mts

Or tsx:

npx tsx replay.mts

The recording covers command calls. Control notifications still need a live tmux server (testing guide).

tmux MCP

npm · GitHub · Homepage · Guides · Tools · Resources · API Explorer

An MCP server for interacting with tmux - powered by the above core library (like libtmux-mcp!) It exposes tools for inspecting sessions, reading pane output and running commands.

Start a separate tmux server for the demo:

tmux -L libtmux-ts-mcp-demo -f /dev/null new-session -d -s demo

Use this command with a client that launches stdio MCP servers:

LIBTMUX_SOCKET=libtmux-ts-mcp-demo npx -y @libtmux/mcp

It waits for MCP requests over stdin; it is not an interactive terminal app. The guides cover connecting a client and selecting a tmux socket.

After closing the client, remove the demo server:

tmux -L libtmux-ts-mcp-demo kill-server

Workspace manager

Workspace library

npm · GitHub · Homepage · Guides · API Explorer

Build a tmux session from a configuration object with applyWorkspace. This is like tmuxp's workspace builder, but in TypeScript - and with the newer features the python version doesn't have: batching, control mode, etc.

npm install @libtmux/workspace libtmux

Save as workspace.mts. Like the core example, this uses a separate server and removes it afterward.

import { Server } from "libtmux";
import { applyWorkspace } from "@libtmux/workspace";

const server = new Server({
  socketName: `libtmux-workspace-demo-${process.pid}`,
  configFile: "/dev/null",
});

try {
  const session = await applyWorkspace(server, {
    session_name: "demo",
    windows: [
      { window_name: "shells", panes: ["printf 'hello\\n'", "pwd"] },
    ],
  });
  console.log(session.name, session.windows.at(0)?.panes.length);
} finally {
  await server.kill();
}

Run with Node:

node --import tsx workspace.mts

Or Bun:

bun workspace.mts

Or tsx, installed as above:

npx tsx workspace.mts

Each prints:

demo 2

Workspace CLI

npm · GitHub · Homepage · Guides · CLI reference · Builder API

This is like tmuxp, but in TypeScript! Load tmux workspaces from YAML or JSON, or capture a running session as a workspace file. The CLI and workspace library are separate implementations; they don't accept exactly the same configuration fields. Uses the libtmux core library.

Use a current Node 22+ release for the CLI.

npx -y @libtmux/workspace-cli --help

Save as workspace.yaml:

session_name: demo
windows:
  - window_name: shells
    layout: even-horizontal
    panes:
      - "printf 'hello\\n'"
      - pwd

Load it detached on a separate socket:

npx -y @libtmux/workspace-cli load ./workspace.yaml -L libtmux-workspace-demo -f /dev/null -d --json

Capture that session:

npx -y @libtmux/workspace-cli freeze demo -L libtmux-workspace-demo --json

Remove the demo server when finished:

tmux -L libtmux-workspace-demo kill-server

Intentions and goals

I am porting libtmux to multiple languages. TypeScript is the language I use second most after Python. Beyond that, there's also C++, Elixir, Ruby, Rust, so on. That means I can be docked fairly for spreading my attention across a large estate, meaning I may miss oppurtunities to leverage TS in the most elegant way. In those cases I'd be very grateful to get feedback how it could be done better, as the APIs aren't stable yet!

You don't need a wrapper or library to use tmux. It's a CLI app perfectly doable via command line itself thanks to its targets (UIDs that point to Session, Window, Pane) and formats. There's also control mode.

However, the tmux object graph itself is very elegant and easy to wrap one's brain around - I think it translates perfect to an OOP model. Also, things like control mode can be wrapped in a way that uses a language's unique strengths. TypeScript - being typed - made this so much better than it'd be with plain ECMAScript, having a sense of security like that is nice, Python didn't always have annotations and mypy.


r/typescript • • 19d ago

Joist 2.5 -- State Machines, PostgreJS, and Read Locks

10 Upvotes

Hello r/typescript ! Another Joist release is out with some cool new features:

https://joist-orm.io/blog/joist-2-5/

Just posting as an FYI & casual reminder that your ORM does not have to be "just a query builder". (ducks) 😅


r/typescript • • 18d ago

Galactica, a TypeScript codebase map for developers and agents

0 Upvotes

As a part of experiments exploring how we as humans fit into development processes, I built Galactica. I wanted a way to see how a codebase fits together, and to give my coding agent that same information before it starts changing things.

I rather suspected than expected this, but it also makes agents more efficient.

It follows imports and exports to build a map of the repository. The agents get neat commands for questions like "where is this defined?", "what depends on this file?" and “which tests reach it?”, I get an interactive HTML page where I can explore those same relationships.

There’s also a skill that tells the agents when to use it: get an overview before diving in, check dependents before editing, and check for new import cycles afterward.

It runs locally, doesn’t execute the code it analyses, and usually needs no configuration. It supports JavaScript too, including JSX and the script sections of Vue, Svelte and Astro files.

It's still early. I’d be interested to hear whether it helps you find your way around a repository, whether it helps you in your development processes you think it falls short. Does this answer questions you currently piece together manually, or does your existing setup already cover them?

I found it quite useful for situations where agents prototype something quickly and I want to get a good understanding of what's actually being built.


r/typescript • • 20d ago

Feeling lost with all the TypeScript options now. What are you actually using?

52 Upvotes

So the "too many JS frameworks" problem has kind of turned into "too many TypeScripts" lol. Regular TS, the Go port, the Rust ports, and whatever else shows up next week.

I've always just used plain TypeScript and never really thought about it. But now with 7 out, I keep seeing people say to just stay on 6, and honestly I don't know what to do anymore.

Is 7 actually worth upgrading to, or is it still too early? Are any of the other implementations worth looking at, or should I ignore them and stay on the boring option?

What are you all running in real projects? Curious if there are any gotchas before I touch my setup.


r/typescript • • 20d ago

What are you using for linting/formatting these days?

31 Upvotes

I've always used ESLint + Prettier, but it was getting slow and heavy, so when I found Biome I switched without thinking twice. Honestly really happy with it so far.

Lately though, Oxc (oxlint + oxfmt) has been looking pretty tempting. Has anyone made the jump, or is thinking about it?

Curious what you're running right now and why. Any gotchas, missing rules/plugins, or things you'd recommend? Especially interested in how they handle bigger codebases and type-aware linting.


r/typescript • • 20d ago

RefQL's 5th anniversary — still waiting for its first fan club

1 Upvotes

Hi,

RefQL is celebrating its 5th anniversary!

It's a TypeScript library for writing type-safe relational queries.

After 5 years, it still doesn't have many users, but I've been using it myself in production for years without problems. So at least it has one happy customer.

The idea is to make relational queries easier to write and read, without losing type safety and IntelliSense.

For example, in some ORMs you have to write things like id: true and firstName: true just to select a few fields. I wanted to keep this a bit simpler.

With RefQL you can do:

const { Player, Team } = refql.tables.public;

const readPlayers = Player([
  "id",
  "firstName",
  Team(["name"])
]);

const players = await readPlayers();

The output type is inferred automatically, also for the referenced Team.

You can also use filters, sorting, pagination, inserts, updates, deletes and raw SQL.

For PostgreSQL, RefQL can introspect the database and generate the tables and references for you.

I've also added some comparisons with Drizzle, Kysely and Prisma in the README.

GitHub: https://github.com/tureluren/refql


r/typescript • • 21d ago

Designing hardware in Typescript

9 Upvotes

Simten is an open source (https://github.com/simtenHQ/simten) HDL where circuits are written in TypeScript. The simulator is Ts as well, so everything runs in-process in Node or the browser.

I built a game around it to showcase the platform, https://play.simten.dev/

So essentially write a circuit in the editor to match the spec, it simulates live on the canvas on the right. You can toggle inputs, step the clock back/forward, drill into parts to view internals etc.

Here is the basic syntax for a half adder (GIF shows a full adder built from two of these):

import { bit, circuit } from '@simten/core'
import { And, Xor } from '@simten/core/std'

const HalfAdder = circuit('HalfAdder', {
  inputs: { a: bit, b: bit },
  outputs: { sum: bit, carry: bit },
  nodes: { xor: Xor, and: And },
  connect: ({ inputs, outputs, nodes: { xor, and } }) => [
    inputs.a.to(xor.a, and.a),
    inputs.b.to(xor.b, and.b),
    xor.out.to(outputs.sum),
    and.out.to(outputs.carry),
  ],
})

You can also run circuits headlessly in node:

import { simulate } from '@simten/core'
const sim = simulate(HalfAdder)
sim.set({ a: 1, b: 1 })
sim.read() // { sum: 0, carry: 1 }

Because it's all in-process, you can use npm packages at the transpile step. For example, this calls figlet to bake ASCII art into a ROM and streams it to a console (press play in the bottom left and change "Simten" text on line 7 ): https://simten.dev/circuit?example=figlet

For when you are sick or typing there's an mcp server, so you can ask your assistant for a circuit and it writes it, tests it and opens it for you to view. Passing it proper hardware specs I have built RISC-V cpus with it among other things. it has been a great learning experience building it. Feedback and/or contributions welcome!


r/typescript • • 21d ago

How do you bridge TypeScript DTOs and Sequelize model instances?

8 Upvotes

Good day Seniors. I'm curious how other TypeScript + Sequelize users deal with the friction between DTO Types and Sequelize model instances. A common pattern I see is simply asserting types

findAll: async () => {
  const data = await SampleModel.findAll({
    where: { status: true },
  });

  return data as unknown as SampleDTO[];
},

but at runtime it's still a Sequelize instance with dataValues, instance methods, metadata, etc., so the types don't really reflect the actual object.

you can also use { raw: true } which returns plain objects, but I've run into dialect-specific issues. For example, boolean fields stored as TINYINT may come back as 0/1 instead of being cast to true/false by Sequelize, creating another mismatch between runtime values and DTO types.

I've also experimented with:

1. Repository mapping

  return data.map(
    (item): SampleDTO => ({
      id: item.id,
      name: item.name,
      ...
      status: item.status,
    }),
  );

This gives a clean type but introduces mapper maintenance and some potential runtime overhead.

2. Zod parsing

{ SampleSchema.parse(data);}

I've also seen people run records through Zod schemas/parsers to normalize and validate the shape, but that adds another layer of processing as well.

For teams that have stayed with Sequelize (rather than Prisma, Drizzle, TypeORM, etc.), what's your preferred approach for bridging the gap between Sequelize's runtime objects and TypeScript DTOs?

Have you found a pattern that balances type safety, runtime correctness, and performance without excessive boilerplate?

I'm still learning different ORMs. Altho i had a good experience with Prisma's generated types and type casting, i'm curious how experienced Sequelize users approach this problem.


r/typescript • • 21d ago

I got a decorator to type check the generic of the class it's on and I'm way too happy about it

2 Upvotes

In my framework, every handler has to write its route twice. Once in the decorator because the runtime needs the string, and once in the generic because the types need it.

@Route('ban')
class Ban extends Handler<'kick'> {}
// no errors. cool. love that for me

That compiles. The handler for ban now thinks it's handling kick and TS is completely fine with it.

And yes, I tried only writing it once. class Ban extends Route('ban'). It worked(?), but every handler read like mixin tomfoolery, and go-to-definition took you to a generated base class instead of the real one, and I just didn't like how it looked, so I went back to writing it twice. But if I'm writing it twice, the compiler might as well make sure I wrote the same thing twice.

First problem is that a decorator only gets the class, so you need some way to read the generic back off it, and if the class doesn't use the generic, you can't:

abstract class Handler<Route extends string> {}
class Kick extends Handler<'kick'> {}

// string, not 'kick'
type Read = Kick extends Handler<infer Route> ? Route : never;

// also compiles lmao
const oops: Handler<'ban'> = new Kick();

That's structural typing, since an unused type parameter basically doesn't exist, so it has to be on a property. But I also don't want a real property on every handler, so:

declare const route: unique symbol;

abstract class Handler<Route extends string> {
    declare readonly [route]?: Route;
}

type AnyClass = abstract new (...args: never[]) => unknown;

type RouteOf<Class extends AnyClass> =
    InstanceType<Class> extends { [route]?: infer Route extends string } ? Route : never;

declare so none of this gets emitted, and it's optional so nobody ever has to set it. Now RouteOf<typeof Kick> is 'kick', and that oops line is an error as a bonus.

Also that never[] looks weird, but unknown[] doesn't work because parameters are contravariant, so unknown[] rejects any class whose constructor takes a string, and never[] accepts all of them.

Now compare the two:

type Same<Left, Right> = [Left] extends [Right] ? ([Right] extends [Left] ? true : false) : false;

You need those brackets, because without them the conditional distributes over the union, Same<'ban' | 'kick', 'ban' | 'kick'> comes out as boolean, and a perfectly correct handler gets rejected. And it has to check both ways, because one way lets @Route('ban') through on a Handler<'ban' | 'kick'>.

Now the part I like:

type Checked<Routes extends string, Class extends AnyClass> =
    Same<Routes, RouteOf<Class>> extends true
        ? Class
        : ['the decorator and the generic disagree', { decorator: Routes; generic: RouteOf<Class> }];

function Route<Routes extends string>(...routes: Routes[]) {
    // Class only shows up inside a conditional type here
    // and TS still infers it. still feels illegal
    return <Class extends AnyClass>(target: Checked<Routes, Class>): void => {
        console.log(routes, target);
    };
}

Look at target. Its type is a conditional that depends on Class, and Class is the thing TS is supposed to be inferring from target. That looks circular and you'd expect it to just break or something. But when the parameter is a conditional type, TS infers into both branches (inferToConditionalType in the checker if you want to go look), and the true branch is just Class. So Class gets inferred as the decorated class, then the conditional resolves using it, and if the routes are different the parameter turns into a tuple that a class can't be assigned to. And the message shows up right in the error:

Argument of type 'typeof TooMany' is not assignable to parameter of type
'["the decorator and the generic disagree", { decorator: "ban" | "kick"; generic: "ban"; }]'.

Wow magic. It also works with both standard and experimental decorators. Here's all of it in the playground.

Also I use this same conditional for attaching plugins, and over there it fixes an actual bug. The obvious way to write it is Class & Check<Class>, and that broke inference on generic plugin classes in both tsc and tsgo for some reason.

This is all from seedcord, a TypeScript framework that I've been building. Here's the real file, and that version also errors if the route doesn't exist. I've done a lotta TS shenanigans in this repo, so I'll prolly post about some of the other tricks too.


r/typescript • • 24d ago

Config format parser written entirely in TypeScript types

Thumbnail
github.com
5 Upvotes

r/typescript • • 24d ago

Has anyone used branded types to make a missing permission check a compile error?

13 Upvotes

Our API handlers load a record, call can(user, 'delete', doc), then call the service. Every few months someone adds a route and skips the middle step. Review misses it because the diff looks fine.

I've been playing with this:

type Authorized<T, A extends string> = T & { readonly __authorized: A };

function authorize<T, A extends string>(user: User, action: A, resource: T): Authorized<T, A> { if (!can(user, action, resource)) throw new ForbiddenError(); return resource as Authorized<T, A>; }

async function deleteDoc(doc: Authorized<Doc, 'delete'>) { ... }

Calling deleteDoc(doc) without going through authorize no longer compiles, and a doc authorized for 'edit' can't be passed where 'delete' is required.

Problems I can already see:

  • Anyone can still write as Authorized<Doc, 'delete'>, so we'd need a lint rule banning that cast outside one file.
  • The brand only proves the check passed once. If a job runs an hour later, or the user gets removed mid-request, it's stale.
  • List endpoints don't fit. I don't want to authorize 500 rows one by one; that filter belongs in the query.
  • It spreads into every service signature, and some people on the team already hate it.

Is anyone running something like this in production? Did it hold up, or did you go back to middleware plus a test that hits every route as a low-privilege user?


r/typescript • • 25d ago

Conditional types [Help!]

0 Upvotes

I recently released a 45-seconds YouTube video on conditional types, check my reddit profile for it. I need your feedback before I double down. Let me know what you think. Here is the script:

> Conditional types

In JavaScript, you have a conditional operator:

const ternary = typeof 'Wasim' === 'string' ? true : false 

console.log(ternary) // true

It is also known as ternary operator.

Similarly, In TypeScript, you also have a conditional operator for types:

 type Ternary = 'Wasim' extends string ? true : false // true

This is refer to as a conditional type.

Conditional types allow us to conditionally check for types that match certain criteria and decide what to do if they do match those criteria and what to do if they don’t.

Here is one example:

type Generic<T> = T extends string ? 'Wasim' : 25

type Test1 = Generic<'Hi'> // 'Wasim'

type Test2 = Generic<143> // 25

Here, we said if type argument is a subtype of string, then return type 'Wasim', if not, then return type 25.

You can return never instead of 25, if condition fails. It’s equivalent to returning nothing.

//

P.S.

I am testing content from my upcoming TypeScript book to gather early feedback.

I decided to start small with a tiny video, instead of fantasizing about releasing a value-packed longer video. It's harder to do that without any momentum. I made it quickly and decided not to obsess over scripting, editing, and fixing audio by rerecording. Those are my fun-killers. I want it to be quick, fun, and imperfect. The goal was progress, not perfection. Wish me luck!


r/typescript • • 25d ago

X3Bun a Hono/TanStack Start/tRPC/Better-Auth Turborepo Starter App

Thumbnail
github.com
0 Upvotes

This is simply a starter template that I use and I thought of sharing

  • Bun optimized
  • Front End: Tanstack Start, Tanstack Query, and Shadcn
  • Backend: Hono with tRPC
  • Authentication: Better-Auth
  • Repo Management: Turborepo

I encourage you to check and share your opinion


r/typescript • • 25d ago

Which AI code review tool would you pick for a TypeScript monorepo??

0 Upvotes

i want to add an AI reviewer to our PR workflow and i've narrowed it down to these:

  1. coderabbit
  2. bugbot
  3. claude code review
  4. codex review

we're a pnpm + turborepo monorepo, around 30 pkjs, Next.js frontend and a bunch of Node services, strict mode everywhere. about 10 devs and a lot of the code is coming from agents now, so PRs are bigger than they used to be.

The main thing i care about is whether it understands types across packages. if someone changes a shared type in one package i want it to notice what breaks in the others, not just comment on the file that changed.

if you had to pick one or two from this list for a TS monorep, which would you pick and why?


r/typescript • • 26d ago

TypeScript framework for building AWS apps

Thumbnail
syncploy.com
0 Upvotes

As a developer with zero knowledge of AWS, once I tried to deploy app on AWS, I had lost $100 overnight by accidentally configuring large EC2 instance. That demotivated me to such extent that I decided to shut it off. But accidentally losing in many AWS is way easier for newbie devs.

So I decided to build a framework in TypeScript so devs with near zero knowledge can ship highly sophisticated AWS apps. I have also added strong for LLM's hence coding agents will be able to work with it seamlessly.

I have validated this framework by using it in my own personal project to ensure experience the perks - https://github.com/harsh-vardhhan/EHR-backend

Though this is a fun project, I plan to maintain it and even planning to use it at my workplace.


r/typescript • • 27d ago

How (and where) is “T extends U” in generics defined?

1 Upvotes

Or in other words: “can I please have a TypeScript 5/6/7 language spec?”

——-

Using “extends” in a TS generic type-param constraint is straightforward to understand if you’re only concerned with Java/C#-style single inheritance for classes - and one can stretch that to include interface types once you wean-off Java/.NET nominal typing and get comfortable with structural typing, then it’s straightforward to reduce it to “T extends U means “T must subclass U” - or even “A T-shaped plug can be stored in a U-shaped hole”.

But my personal intuition breaks down when the extends constraint is used with other kinds of types, especially when the concept of subclassing or specializing or “extending” is inverted:

Consider type Two = ‘foo’ | ‘bar’; - if I then define type Three = Two | ‘baz’; then intuitively one can say “Three extends Two” (that is, the set of possible values for Three is extended from the set of values for Two” - but a Three-shaped plug does not fit into a Two-shaped hole: ’baz’ is not a Two. But saying “Two extends Three” out-loud feels weird. The same applies to enum types too, surely?

Or consider function-types, which can be expressed as either a function-declaration: type MyFuncType = (arg: ArgType) => ReturnType; or type MyFuncType { (arg: ArgType): ReturnType; } (where the more verbose syntax permits adding properties to a function object). Supposing this MyFuncType is used as U when T extends U then I’ll admit I have no intuition what a possible T might entail outside of Currying (but Currying is just FP’s take on The Decorator Pattern (lol) and doesn’t apply (hah) to generics. But after having thought about it, I imagine FuncT extends FuncU would allow for argument type contravariance with return-type covariance (or is it the other way around?), so a plug shaped like type T = (arg: ‘foo’ | ‘bar’) => Number fits into a hole shaped like type U = (arg: ‘foo’) => void - but as above, it pains me to say that “T extends U” in that situation: I consider these entirely distinct function-types. I’m also unsure how ... and optional params complicate the rules.

…and never mind the contortions over array-type covariance. And the new const T type constraint - which I only learned of this morning.

Unfortunately and annoyingly, the current TypeScript Handbook section on Generics and Advanced Typing doesn’t really cover any of this in depth or provide an intuitive way of thinking about it :S


r/typescript • • 27d ago

New Stack Alert!!

0 Upvotes

https://getforma.dev a TypeScript framework with no V8/Node on the server and no Virtual DOM on the client. It compiles TSX into a binary format called FMIR at build time so a Rust server can render SSR HTML directly, and only ships tiny signal islands to the browser. I’ve been using it to build apps with AI lately and it seems because the contract between TS and Rust is so strict, it's been ridiculously fast and efficient. Not bloat.


r/typescript • • 29d ago

End-to-end types over WebSockets: the server documents itself as AsyncAPI, the client is generated from it

9 Upvotes

Hi all, I want to share an open-source TypeScript library I built (chanx-js, MIT) to type both ends of a WebSocket from one source, without sharing a types package between the frontend and the backend.

With REST we have OpenAPI and generated clients. With WebSockets I kept ending up with JSON.parse(event.data) giving me any, a hand-written union of message types on the client, and nothing stopping it from drifting away from what the server really sends.

So in chanx-js:

  1. On the server you declare messages with any Standard Schema library (Zod, Valibot, ArkType), and the payload types are inferred from the schema.
  2. The server serves an AsyncAPI 3 document built from those handlers.
  3. npx @chanx-js/codegen http://localhost:8000/asyncapi.json generates the client types from it.

On the server, the path params, the payload and what the handler may send are all typed:

const Chat = defineMessage('chat', z.object({ text: z.string() }));
const Notice = defineMessage('notice', z.object({ text: z.string() }));

consumer('/ws/chat/{room}', { name: 'chat' }).on(Chat, { output: Notice }, (m, ctx) => {
  m.payload.text; // string
  ctx.params.room; // string, parsed from the path by a template literal type
  return Notice.create({ text: m.payload.text }); // anything but Notice is an error
});

On the client, request() knows the reply type, and a wrong payload doesn't compile:

const connection = client.connect(chat, { params: { room: 'lobby' } });

const reply = await connection.request({ action: 'chat', payload: { text: 'hi' } });
reply.payload.text; // string, from the handler's `output`
connection.send({ action: 'chat', payload: { txt: 'hi' } }); // compile error

The contract goes through AsyncAPI instead of shared TS code, so the server doesn't have to live in the same repo, or even be written in TypeScript.

Repo: https://github.com/chanx-dev/chanx-js

It's still new, so if you run into problems or have ideas for the types, please open an issue or a discussion. Stars and PRs are welcome too.


r/typescript • • Oct 26 '26

Double errors: Parameter 'err' implicitly has an 'any' type | Argument of type err:any is not assignable

0 Upvotes

Title - I don't understand why this code has been getting two errors. I have tried to declare the string type, assign some values but none of these worked. Could anyone point me in the right direction?

import {promises as fs} from 'fs';

class Logger {
    //some code lines..
    
    private flush(): void {
        if (this.buffer.length > 0) {
            const logLines = this.buffer.join('\n') + '\n';
            const err = this.buffer.fill('error')
            /*ERROR #1 Argument of type  "(err: any) => void" is not assignable to parameter of type "(ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined; }) | BufferEncoding | null | undefined". */
            /*ERROR #2 Parameter err implicitly has an any type*/
            fs.appendFile(this.logFile, logLines, (err) => {
                if (err) {
                    console.error('Error writing log file:', err);
                }
            });
            this.buffer = [];
        }
    }
    //one more stop method ..
}

r/typescript • • Oct 26 '26

Typescript to python or rust?

0 Upvotes

How easy or hard is it for someone with JS and TS background to learn python or rust? I deff want to add a skill to my profile as most jobs ask for multiple programming languages. Any suggestions?


r/typescript • • Oct 25 '26

Help for a portfolio

0 Upvotes

Hello, everybody, hope you're having a nice day. Let me present myself, i am a Italian teenager, that is learning typescript, for some money for my little cousin birthday. And I actually went for TypeScript, as I love strict languages, such as Java,Rust,TypeScript, and others. Now, for my portfolio, I was trying to create a solar system, with add, that you can create another thing by this button. But it doesn't work, can someone please help me understand this (probably simple) problem?

const Button = document.getElementById("button");


const buconero = function() {
    const valvia = document.createElement("div")


    valvia.style.width = "50em"
    valvia.style.height = "50em"
    valvia.style.backgroundColor = "rgb(0, 0, 0)"
}


Button?.addEventListener("click", buconero)

r/typescript • • Oct 24 '26

Want Advice for Learning Typescript

11 Upvotes

Hello TypeScript developers!

I am a web developer currently building projects with React and JavaScript, and I'm planning to start learning TypeScript (because I suck at Type checking and Type validation).

please give me some advice on few things:

  • What's the best resource for learning typescript?
  • What concepts should I focus on first?
  • What project would be good to build alongside learning it?

r/typescript • • Oct 23 '26

Rune 1.3 is out: adds TypeScript support, a Helix editor, Kitty graphics and OSC-7501

30 Upvotes

Author here! I'm very excited to announce that we just released v1.3. Rune is an IDE and terminal multiplexer that we just open sourced a few months ago.

In this release, we also fixed many usability issues, particularly on Linux. If your OS reserves many Super/Windows key combinations, you can now use <alt> as your <meta> modifier. For non-US keyboard layouts, you can reserve the right Alt key for entering special characters and keep the left Alt key for Rune key bindings.

Some of the highlights:

- A new graphics pipeline powered by ebiten.
- Typescript is now a tier 1 language (beta)
- A new helix editor
- Headless mode and a new docker image to run Rune in headless mode
- OSC-7501 implementation and new API in the SDK for extensions and plugins through runectl
- Workspace session restoration
- A billion other things

This release has been 2 months in the making so it's a bit bigger than we originally intended.

Thanks to all the contributions from the community!

https://rune.build/blog/rune-1-3-release


r/typescript • • Oct 22 '26

Type inference from .sql files by colinhacks (Creator of Zod)

Thumbnail x.com
169 Upvotes

It uses content mappers, a new feature of TypeScript 7.1 (Beta).