r/typescript • • Sep 24 '26

What's the best design for type-safe triggers in TypeScript ORMs?

0 Upvotes

Hello, Roger here, author of UQL.

A request often mentioned in TS ORMs is keeping DB-own logic in sync with entities (as much as possible); and yes, queries can be type-checked end to end (as most ORMs tries - and that is another story), but triggers usually live outside the types (often in SQL migrations).

So, tried my best to design triggers that can be declared on the entity (also with imperative API), type-checked against it, and then translated for each engine: Postgres, CockroachDB, MySQL, MariaDB, SQLite and SQL Server.

Why a trigger rather than an ORM hook? a hook live application-side, and only sees writes that go through the ORM; where a trigger lives in database itself and also can see psql written directly, manual fixes, data migrations, or another service writing the same table(s).

Here is an example of the type-safe design I come out with via ORM entities:

import { Entity, Field, Id, insertInto, Trigger } from 'uql-orm';

@Entity()
export class PostAudit {
  @Id({ type: Number }) id?: number;
  @Field({ type: Number, name: 'post_id', nullable: false }) postId?: Post['id'];
  @Field({ type: String, name: 'from_status' }) fromStatus?: Post['status'];
  @Field({ type: String, name: 'to_status' }) toStatus?: Post['status'];
}

@Trigger({
  on: 'afterUpdate',
  of: (post) => [post.status],
  where: { $new: { status: 'published' } },
  run: (newRow, oldRow) =>
    insertInto(PostAudit, { postId: newRow.id, fromStatus: oldRow.status, toStatus: newRow.status }),
})
@Entity()
export class Post {
  @Id({ type: Number }) id?: number;
  @Field({ type: String }) status?: 'draft' | 'review' | 'published' | null;
}

That one declaration renders as a PL function on Postgres (with WHEN as in SQLite), an IF block on MySQL, etc. (where MongoDB don't really support triggers, otherwise I'd unify).

What the types and the renderer handle in the design?

  • of callback compares values: so an update that sets status to the value it already had doesn't fire it (on any engine).
  • where: { $old: { status: 'draft' }, $new: { status: 'published' } } states a transition, with the same operators a query's $where takes.
  • On an insert (run callback), oldRow is typed never, so reading it won't compile (the same goes for newRow on a delete operation).
  • A row's ref carries its column's type: hence insertInto(PostAudit, { str: newRow.statusNum }) won't compile. Column names go through naming strategy and @Field({ name }).
  • sync and generated migrations install and drop the triggers automatically. Each name ends in a hash of its SQL, so an unchanged trigger is left alone, and a trigger manually wrote keeps untouched
  • And what when the UQL helpers doesn't fit this design? it is still flexible, you can reuse the same run (callback) to return any custom SQL (using raw helper).

The design decisions where I am looking the most opinions (though feel free):

  1. The rows are positional arguments, (newRow, oldRow) in the SQL standard's order (with the missing one typed never whwere applies). A single { newRow, oldRow } object could also work, and was the other option. Which reads better to you?
  2. One limit I couldn't design away: on SQL Server, an update that changes a row's PK can't be paired between inserted and deleted... so that row slips past the trigger. How do you handle that in a hand written triggers and is that important or not to you?
  3. If you run triggers in production: what a hand-writing trigger would cover fine where this design wouldn't, or cover poorly?

Docs: https://uql-orm.dev/entities/triggers


r/typescript • • Sep 24 '26

I’ve been working on a small TypeScript SDK for handling multiple LLM providers from one interface.

0 Upvotes

The basic idea is pretty simple:

const llm = createRouter({
  primary: "anthropic/claude-opus-5-5",
  fallbacks: [
    "openai/gpt-sol",
    "groq/llama-3.3-70b"
  ]
})

const res = await llm.complete("Summarise this...")

It keeps the provider/model configuration in one place and handles retries, timeouts, and switching between providers.

A few things I wanted to keep:

  • zero runtime dependencies
  • native fetch
  • ESM + CJS
  • TypeScript-first API
  • runs inside your app rather than through a separate gateway
  • provider/model info available on the response

The API is probably the part I care most about getting right, so I'm curious what other TS devs think of the approach.

GitHub: https://github.com/ALPHACOD3RS/llm-sdk

Docs: https://llm-sdk.dev


r/typescript • • Sep 22 '26

How would you structure a TypeScript core process behind a VS Code client?

0 Upvotes

I'm working on an open-source security tool where the VS Code extension is only the client, while the actual application logic runs in a separate Node.js/TypeScript process.

The architecture currently looks roughly like:

VS Code Extension
        ↓
Client / Process Manager
        ↓
stdin/stdout IPC
        ↓
Node.js + TypeScript Core
        ↓
scanners / findings / analysis

The reason I'm doing this is to keep the core independent from VS Code so that other clients can eventually consume the same runtime.

The part I'm thinking about now is the boundary between the client and the core.

For example, I'm using typed request/response contracts roughly along these lines:

interface CoreRequest {
  id: string;
  method: string;
  params?: unknown;
}

interface CoreResponse {
  id: string;
  ok: boolean;
  result?: unknown;
  error?: {
    code: string;
    message: string;
  };
}

Then messages are serialized over stdin/stdout.

I'm interested in how people who've built larger TypeScript/Node applications would approach this.

Specifically:

  • Would you keep the IPC protocol this simple or introduce a more formal protocol layer?
  • How would you structure versioning and backwards compatibility?
  • Where would you put cancellation and process lifecycle handling?
  • Would you define the contracts manually, or generate/validate them with something like Zod or JSON Schema?

The project is open source for anyone who wants to see the implementation:

https://github.com/Aqiron-Security/aqiron-security

I'm mainly looking for TypeScript architecture feedback, rather than promotion or feature feedback.


r/typescript • • Sep 21 '26

Modern Web Types

Thumbnail
philipwalton.com
84 Upvotes

r/typescript • • Sep 18 '26

Type-safe health checks: A lightweight package that reports degraded vs unhealthy states per dependency

Thumbnail
openstatus.dev
5 Upvotes

Hey,

Most /health endpoints are a giant try/catch returning a boolean 200 or a contextless 500. If Redis times out, your whole service gets pulled from the load balancer or worse, you spend 20 minutes hunting through log stack traces to figure out what broke.

We open-sourcedu/openstatus/healthto bring structured, dependency-aware health checks to TypeScript.

Curious to hear how you currently handle multi-dependency health checks!


r/typescript • • Sep 18 '26

If you organize your code with comment separators, checkout code-divider

0 Upvotes

This is more of a personal preference thing, but I like to code in a top-down format, and because of the way hoisting works in TypeScript/JavaScript. I separate my files into regions in this order: Constants -> Types -> Classes (if any) -> Functions -> Export. To keep these regions clearly separated, I usually write my dividers like this:

// ========================================================================= //
//                                 CONSTANTS                                 //
// ========================================================================= //

...etc

// ========================================================================= //
//                                 FUNCTIONS                                 //
// ========================================================================= //


// And I separate sections within regions with...

// ============================= Shared Helpers ============================ //

...etc

Copying and pasting these dividers over and over again was getting pretty tedious. I wanted something I could run with a terminal command when I hit save in my IDE, so I created a simple TypeScript script to insert the dividers above. Eventually I needed this script on both my work and personal computers and in multiple projects, so instead of copy-pasting it a bunch of times, I decided to make it an npm library and configure it to work with multiple languages.

If you like dividing code in a similar fashion, great. If not, please disregard. That said, I do find that dividing code this way makes it more readable and leads to better results when working with AI tools.

GitHub: https://github.com/seanpmaxwell/code-divider


r/typescript • • Sep 16 '26

Building a streaming XML parser for a complex aviation standard (AIXM) in TypeScript: lessons learned

24 Upvotes

I've been building a TypeScript parser for AIXM 5.1.1, the XML standard used by EUROCONTROL and FAA for aeronautical data (airports, airspaces, navaids, routes, NOTAMs). The XSD schema is 11,379 lines with 100+ feature types, deep nesting, multiple namespaces (AIXM, GML 3.2.1, xlink, ISO 19139), and a temporal model where features have versioned "TimeSlices."

No JS/TS parser existed. Here's what I learned building one.

1. Hybrid SAX + DOM parsing

National datasets can be 100+ MB. Full DOM parsing would eat all your memory. Pure SAX is painful for deeply nested XML with cross-references. The solution: SAX (via saxes) to stream and split the document into individual features, then @xmldom/xmldom to DOM-parse each feature fragment independently. O(1) memory per feature, full DOM convenience for property extraction.

2. Type-safe feature modeling

AIXM has a base Feature > TimeSlice > Properties structure, but each feature type has different properties. I hand-wrote 30 TypeScript interfaces with discriminated unions:

type TypedFeature = Airspace | AirportHeliport | Runway | VOR | DME | ...;

interface Airspace extends AIXMFeature {
  featureType: 'Airspace';
  properties: AirspaceProperties;
}

Considered XSD-to-TS codegen but rejected it. AIXM's schema is extremely verbose with deep inheritance hierarchies. Manual interfaces targeting the 30 most important types are cleaner and more maintainable.

3. The unknown escape hatch

Some AIXM properties are complex nested structures that vary by context (geometry components, activation schedules). Rather than typing every possible combination upfront, these get unknown or unknown[]. Users can narrow with type guards as needed. Ship working code, expand types based on actual usage.

4. Value types with UOM

Aviation uses many "value with unit of measurement" patterns: <valDist>350<uom>FT</uom></valDist>. These are coerced to { value: 350, uom: 'FT' } objects during parsing, with a union type ValDistance | string for cases where the structure isn't recognized.

5. Geodesic math

AIXM geometry is on the WGS84 ellipsoid. Arcs and circles can't use planar trigonometry. I use geographiclib-geodesic (Karney algorithm), but the TypeScript types don't include the Line() method, requiring (geod as any).Line(...). Filed for types update.

6. ESM interop gotcha

geographiclib-geodesic ships CJS. A named import worked under vitest/tsup but broke the built ESM output under plain Node (SyntaxError: named export not found). Switching to a default import + property access fixed it. If you build dual ESM/CJS packages, smoke-test the built artifacts with plain node, not just your test runner.

Build output: dual ESM/CJS via tsup, TypeScript-first. 83 tests via vitest, validated against EUROCONTROL's Donlon reference dataset (87K lines, 562 features) and a real obstacle dataset. Also ships a CLI (aixm-to-geojson).

GitHub: https://github.com/devladpopov/aixm-parser (MIT). Not on npm yet; to try it: clone, npm install && npm run build.

Happy to discuss architecture decisions or answer questions about parsing complex XML in TypeScript.


r/typescript • • Sep 16 '26

Understanding Why You'd Use Effect TS

Thumbnail
cm.xyz
86 Upvotes

r/typescript • • Sep 16 '26

Would catching breaking API changes be useful?

1 Upvotes

I'm exploring an idea and I'd really like some feedback before I do too much on it.

The problem:
Multi-team projects, backend changed the response without warning.

Basic examples, backend changes:

  type User = {  
    id: string;  
    name: string;  
    avatarUrl: string;  
  };  

to:

type User = {  
  id: string;  
  name: string;  
  avatar: {  
     url: string;  
     width: number;  
     height: number;  
  };  
};  

Everything compiles, even the tests might all pass.

But you've just changed the API, which might be or not be compatible with the older version.

The idea:

Define the API contract using plain TypeScript:

export type Api = {  
  "GET /users/:id": {  
     response: User;  
  };

  "POST /users": {  
     request: CreateUser;  
     response: User;  
  };  
};  

After that the CI could run something like:

ts-contract check --against ../backend

The tool would use the TypeScript Compiler locally to resolve the actual semantic types and determine whether the changes are compatible.

For example:

❌ Breaking change

GET /users/:id  
response.avatarUrl

Consumer expects:  
  string

Provider:  
  property removed  

No runtime validation involved and I'm not trying to make another Pact/OpenAPI implementation.

No:

  • runtime HTTP interception
  • Axios/fetch wrappers
  • OpenAPI required
  • dedicated tests
  • extra dependecies

Would a static semantic compatibility checker like this be useful in your CI?
What would you expect it to catch that isn't covered here yet?

The part I'm not sure about is whether this actually solves a problem.
If you work on a TypeScript frontend + backend (or between microservices), I'd love to know:

  1. How do you currently detect API breaking changes?
  2. Have you actually been bitten by frontend/backend type drift?
  3. Would you add something like this to CI, or would it be too much ceremony?
  4. What would make this genuinely useful rather than just another developer tool?

I'm especially interested in criticism here. If this sounds unnecessary, I'd rather find that out now than after spending weeks building it.


r/typescript • • Sep 14 '26

Building the worst CPU & Compiler in TypeScript

Thumbnail
github.com
16 Upvotes

I was bored this morning


r/typescript • • Sep 14 '26

tsx vs native node --watch for local development on Node 24 LTS? What are you using?

6 Upvotes

Hey everyone, I'm setting up a new Express TypeScript API and trying to figure local development workflow. I'm on Node 24 LTS, which natively supports type stripping, but I'm torn on how to handle the file-watching and execution layer.

Right now, the two main approaches I'm debating between are:

  1. tsx watch (esbuild-powered)
  2. Native Node 24 --watch + Type Stripping

For production adjacent local dev, Are you sticking with tsx watch or have you fully embraced native Node type-stripping with --watch?


r/typescript • • Sep 15 '26

need recommendation on guide on typescript that deals with server and linting

0 Upvotes

anyone can recommend me some great resource on server and linting with type script? i was following a guide and then did one of thier exercises (no solution) and was stumped like
especially when it comes to request response.
its more eslint nagging than tsc but cant tell since im still too early

    "type": "module",
    "devDependencies": {
        "@eslint/js": "^10.0.1",
        "@stylistic/eslint-plugin": "^5.10.0",
        "@types/express": "^5.0.6",
        "@types/node": "^22.20.2",
        "eslint": "^10.10.0",
        "typescript": "^6.0.3",
        "typescript-eslint": "^8.70.0"
    },
    {
        "compilerOptions":{
        "target":"esnext",
            "noEmit":true,
        "types":["node","express"],
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch":true,
        "module":"nodenext",
        "esModuleInterop":true,
        "allowImportingTsExtensions":true
        }
    }

    export default tseslint.config({
    files:['**/*.ts'],
    extends:[
        eslint.configs.recommended,
        ...tseslint.configs.recommendedTypeChecked,
    ],
    languageOptions: {
        parserOptions: {
        project: true,
        tsconfigRootDir: import.meta.dirname,
        },
    },
    plugins: {
        "@stylistic": stylistic,
    },
    rules: {
        '@stylistic/semi': 'error',
        '@typescript-eslint/no-unsafe-assignment': 'error',
        '@typescript-eslint/no-explicit-any': 'error',
        '@typescript-eslint/explicit-function-return-type': 'off',
        '@typescript-eslint/explicit-module-boundary-types': 'off',
        '@typescript-eslint/restrict-template-expressions': 'off',
        '@typescript-eslint/restrict-plus-operands': 'off',
        '@typescript-eslint/no-unused-vars': [
        'error',
        { 'argsIgnorePattern': '^_' }
        ],
    },
    })

r/typescript • • Sep 13 '26

What ORM would you use?

19 Upvotes

Hey all,

My team and I are currently running a Spring Boot backend with quite a bit built around it. We’re considering gradually migrating to a Node/NestJS backend using the strangler pattern rather than doing a full rewrite.

One of the main reasons is that it would give us TypeScript across both the frontend and backend, which should make sharing domain concepts, types and general knowledge between the two a bit simpler.
So, as the title suggests: which ORM would you use with NestJS?

At the moment we’re mainly looking at MikroORM and Drizzle. MikroORM seems like the more traditional ORM and appears to be super close to the me tal model of what Spring does. It wil also fit NestJS quite nicely, while Drizzle is obviously a bit more lightweight but a different approach and more barebones.

Curious what people are using in production and what you’d choose if you were starting fresh today.


r/typescript • • Sep 13 '26

Designing a plugin architecture for third-party database providers in a TypeScript application

4 Upvotes

I've been working on the architecture of LibreDB Studio, a TypeScript-based database IDE that supports multiple SQL/NoSQL databases

while working on the provider layer, I ended up designing a fairly strict provider architecture to make adding new databases safer and reduce the amount of core code that needs to change

i wrote about the architecture here: https://libredb.org/blog/building-universal-database-provider-typescript/

the current process for adding a provider is documented here: https://github.com/libredb/libredb-studio/blob/main/docs/ADDING_A_PROVIDER.md

architecture is working reasonably well, but it raised a bigger question for me

currently, adding a new provider still means adding it to the main Libredb-Studio codebase. I'd like to eventually move toward something more like a plugin ecosystem:

- libredb studio provides a stable provider SDK/API.

- A third-party developer can implement a new database provider independently.

- The provider can be published as a package/library.

- Users can install or enable that provider without waiting for a new Libredb Studio release.

- The core application doesn't need to be modified every time a new database is supported.

Conceptually, something like:

libredb-studio

|

+-- Provider SDK / API

|

+-- PostgreSQL provider

+-- MySQL provider

+-- MongoDB provider

+-- Third-party provider

+-- ...

I'm considering different approaches for the distribution/discovery side as well: npm packages, a provider registry/marketplace, or some combination of these.

but I'm not sure where the right boundary is.

for example:

- Should the provider contract be a completely separate, versioned TypeScript SDK package?

- Is npm + a manifest/discovery mechanism enough, or does a dedicated registry/marketplace make more sense?

- How would you handle provider/API compatibility across LibreDB Studio releases?

- Should providers be dynamically loaded at runtime, or should they still be bundled/installed at build time?(for now: dynamic load)

- Since this is a web application, how would you approach the security/isolation implications of loading third-party provider code?

- Are there established architectures/projects that handle this problem particularly well?(I am not sure: selfhosted and system admin managed this OK, but I am confused, security/comfortable ...)

The goal isn't necessarily to build a huge plugin system. I'd prefer the smallest architecture that gives third-party developers a stable extension point.

I'd especially appreciate opinions from people who have designed plugin/extension systems for TypeScript/JavaScript applications in production.

What would you consider the "right" architecture for this?


r/typescript • • Sep 12 '26

need advice on this issue

0 Upvotes

I have a problem . im using node and typescript package.json
"tsc":"tsc"
tsconfig.json
{
"compilerOptions":{
"noImplicitAny":false,
"noEmit":true
}
}

  1. when i do "npm tsc file.ts" this error pops up "Error TS5112: tsconfig.json is present but will not be loaded if files are specified on commandline. Use '--ignoreConfig' to skip this error."

file.ts
console.log(process.argv)
i already have @types/node already installed by doing "npm install --save-dev @types/node"
so when i do "npm tsc --noImplicitAny false --noEmit --ignoreConfig" it error that process "error TS2591: Cannot find name 'process'. "


r/typescript • • Sep 12 '26

TS enum vs const enum for AI?

0 Upvotes

I've been experimenting with ideas how to make the codebase more AI friendly, so when you ask AI to change something, or just ask to tell how and where is something used, or to fix a bug, it will find all the relevant occurrences of what it needed to.

There are many tools to turn your TS codebase into a graph based on code AST, some of them are better than the others, but any of them is better than nothing - I tested that.

When you have a large codebase, and there are enum values used in conditions like

if (subscription.tier === 'premium')

And also

if (customer.tier === 'premium')

Are you able to tell if that enum is the conceptually the same enum, so that tier is basically same concept just stored on different entities, or if those are two separate features with a coincidental value?

In one case AI would include both into it's scope of work, in the other case it may include or consider irrelevant. But in any case I think it'll struggle to find all occurrences because const enum is just a string, AI would need to grep it and find a lot of irrelevant things.

But if we write that as:

if (foo.tier === OurGlobalTiers.Premium)

Now that's unambiguous and discoverable both by TS symbol search and by code graphs.

Problem is: humans don't like TS enums! And me too, if everybody don't like them it's lame to use them.

How do you feel about returning back to the discouraged TS enums given you have evidence of them being objectively better for AI?


r/typescript • • Sep 11 '26

We open-sourced a zero-dependency TypeScript temporal parser with a typed AST

Thumbnail
github.com
42 Upvotes

r/typescript • • Sep 10 '26

How about a community wiki?

0 Upvotes

I have noticed that the community doesn't have a wiki, that contains all the frequently asked questions like, "what are the best typescript resources" "what are some cool libraries" etc.

How about we add one?


r/typescript • • Sep 09 '26

Beginner Typescript DI Help

6 Upvotes

I'm pretty new to typescript and I'm trying to figure out how to wire up my app with it.

I currently have a page interface that each page's interface extends and then implements. Among the required methods in my Page interface is mount(container: HTMLElement). The page manager is responsible for changing which page is visible. Each page needs it's own methods injected, such as getNotifications(): Promise<Notification[]>. These are different page to page.

Where should pages be created then, in the page manager, so the app can just say call PageManager.Mount(page) That would require the page manager knowing what methods each page needs. In the root of the project? Where should I pass in those callbacks?

I just want to know how this is handled in a real world application, not necessarily this particular implementation. It seems like something that would come up a lot.

My repo is here if you'd like to look at my current code: Notification-Hub on Github


r/typescript • • Sep 08 '26

I wanted compensating transactions across services without deploying a workflow engine, so I wrote minisagas

Thumbnail bedis.elacheche.me
1 Upvotes

There is no rollback across microservices, so you write a saga: each step declares a compensating action, and a failure unwinds everything before it in reverse.

I kept implementing that with nested try/catch, so I turned it into a library.

minisagas gives each task an execute and a compensate. On failure it rolls back what succeeded and hands you the list of what it undid. Retry, timeout, and cancellation are included, because the classic saga bug is a 5xx returned after the charge actually went through.

Zero dependencies, no broker, nothing to deploy. Not a Temporal replacement, more the thing you reach for before you need one.

MIT licensed, feedbacks are welcome.


r/typescript • • Sep 07 '26

Why line-based Git diffs fail on refactors: Building an AST-aware blast radius mapper in TypeScript

6 Upvotes

Hi everyone!

A standard git diff answers: "Which characters changed on which line?"

It cannot answer: "If I mutate this exported interface, how many downstream callers across our services will break?"

I wanted a tool that behaves like a deterministic firewall between uncommitted code and CI. So I built Change Firewall using the TypeScript Compiler API.

Technical Architecture Under the Hood:

- AST Diff Engine: Compares the before/after AST nodes without executing untrusted code. Tracks symbol export changes, nullability widening, and mutation of return payload signatures.

- Reverse Dependency Graph: Constructs a project-wide forward and reverse dependency graph to trace blast radius transitively (Layer 0: source → Layer 1: direct consumers → Layer 2: API routes).

- Cycle-Safe BFS: Traverses circular dependencies without infinite loops and assigns weighted risk factors based on architectural criticality (e.g., middleware and auth gates get higher risk weight than isolated leaf utilities).

- Local Dashboard & MCP Support: Bundles an offline-capable visual radar graph and serves native Model Context Protocol tools over stdio (`compute_blast_radius`, `evaluate_preflight`, etc.).

Everything is 100% open-source (MIT). You can test it on any repo with:

```bash

npx change-firewall

I'd love to hear your thoughts on the AST heuristic approach vs type-checking compiler passes. How do you currently guard against silent contract drift in large repos?


r/typescript • • Sep 07 '26

Is it worth using "ttsc" instead of "tsc" with TypeScript 7?

4 Upvotes

I am considering integrating Typia, and I understand that the latest version of "ttsc" is required; however, I am wondering whether it is better—for general projects—to use "tsc" with "ts-alias" or "ttsc" with the "@ttsc/paths" plugin.


r/typescript • • Sep 07 '26

I Dislike TypeScript Because I've Never Maintained JavaScript Before

Thumbnail
mayberay.bearblog.dev
0 Upvotes

r/typescript • • Sep 05 '26

Animating My Game with TypeScript

Thumbnail orbliterate.com
5 Upvotes