r/typescript • • 12h ago

Monthly Hiring Thread Who's hiring Typescript developers December

7 Upvotes

The monthly thread for people to post openings at their companies.

* Please state the job location and include the keywords REMOTE, INTERNS and/or VISA when the corresponding sort of candidate is welcome. When remote work is not an option, include ONSITE.

* Please only post if you personally are part of the hiring company—no recruiting firms or job boards **Please report recruiters or job boards**.

* Only one post per company.

* If it isn't a household name, explain what your company does. Sell it.

* Please add the company email that applications should be sent to, or the companies application web form/job posting (needless to say this should be on the company website, not a third party site).

Commenters: please don't reply to job posts to complain about something. It's off topic here.

Readers: please only email if you are personally interested in the job.

Posting BS top level comments that aren't job postings, eg "It's quiet in here" etc is a ban.


r/typescript • • 2d ago

Unframework - The compiler that speaks seven UI frameworks

Thumbnail
unframework.dev
21 Upvotes

Unframework is now available on npm. My dream of writing a component once using TSX, and compiling it to native React, Vue, Svelte, Angular, Solid, Qwik and Astro code, has finally become a reality.

The first components I’ve put through the whole pipeline are a Button, an Input, a Radio, and a Checkbox, and they render the same in all seven frameworks.

"The same" is both a promise and a test. On every PR, CI compiles the components to each framework and checks every output in a real browser: the DOM, the accessibility tree and the pixels have to match one shared baseline, with zero pixel tolerance (visual parity).

I'm also releasing Unframework Preview. It shows every component on all seven frameworks side by side, with controls for their props, so you can see parity for yourself. Build it as a static site and host it anywhere, like a Storybook that speaks seven frameworks at once.

Each output is a real component in its framework's own style: hooks in React, runes in Svelte, signals in Solid. There's no runtime or wrapper in between, so each file depends only on its framework.

Looking forward to hearing your thoughts.

https://unframework.dev


r/typescript • • 1d ago

How do you type and validate env vars at startup in a TS backend?

0 Upvotes

I'm building Elpod, a small decorator-free framework for Elysia on Bun (alpha, so APIs still move), and config is one part I'd like opinions on.

Right now env vars get parsed once at startup into a typed object, and every invalid value is collected into a single ConfigError before the server listens, instead of failing on the first one.

import { defineConfig, env } from "@elpod/core";

export const config = defineConfig({
  port: env.number("PORT", { default: 3000, min: 1, max: 65_535 }),
  environment: env.enum("NODE_ENV", ["development", "test", "production"] as const, {
    default: "development",
  }),
  paymentsUrl: env.url("PAYMENTS_URL", { required: true }),
  timeoutMs: env.duration("REQUEST_TIMEOUT", { default: 5_000 }),
  databaseUrl: env.secret("DATABASE_URL", { required: true }),
});

env.duration wants a unit like 5s or 250ms and gives back milliseconds, and secret values show up as [REDACTED] when you inspect the config. In tests you pass a plain object as the second argument instead of touching process.env.

What I'm unsure about is the typing side. The enum needs as const to narrow to a union, which is easy to forget. Would you rather have a schema lib (zod, valibot, TypeBox) do all of this, or are a few dedicated env helpers fine? And how do you keep secrets out of logs in your own setups?

Docs if you want to look: https://elpod.vercel.app/docs/configuration


r/typescript • • 3d ago

Which of your import cycles are real? What the compiler erases, what it keeps, and what I found in 104 popular repos

0 Upvotes

Most cycle detectors read import statements. That gives a lot of false alarms in TypeScript, because a large share of imports never reach the emitted JavaScript. I spent a while getting this right for a structure linter, and the rules turned out to be less obvious than "import type is free".

What does not create a runtime dependency:

- `import type { X }` and `import { type X }`

- A plain `import { X }` where X is only used in type positions. The compiler drops it, unless `verbatimModuleSyntax` is on, in which case it stays

- A `const enum`, unless `isolatedModules` or `preserveConstEnums` is on, and then it is a real import again

- A dynamic `import()` or a `require()` inside a function body. It runs later, so it does not take part in the load-time loop

What does, even though it looks like a type:

- A class used as a constructor parameter type in a decorated class with `emitDecoratorMetadata`. The class is emitted into `design:paramtypes`, so NestJS and Angular code has runtime edges where the source shows only annotations

- Everything in a `.js` file. There is nothing to erase

- An enum imported from a component file. It is a value

Two patterns produced most of the big cycles I looked at:

  1. Barrels. One `index.ts` that re-exports two files from a higher layer turns a single bad edge into a 20-file cycle, because every sibling that imports the barrel is now in the loop. Importing the sibling file directly usually removes the whole thing.
  2. A registry that constructs its members and passes itself in. `Config` does `new Tool(this)`, `Tool` calls `this.config.something()`. `Tool` only has `import type { Config }`, so no file-level cycle is reported anywhere, and the two classes still cannot be changed or tested apart.

I ran this over the 104 most starred TypeScript repos in the AI ecosystem, with the compiler's own resolution (project references, path aliases, every tsconfig in a monorepo). 260 findings were then checked by hand against the source. The cycle rules held up: the listed edges were real value imports.

Numbers per repo, with every finding and its file and line: https://github.com/PatternVoid/unknot/blob/main/LEADERBOARD.md

The linter is open source and I am its author: https://github.com/PatternVoid/unknot. `npx unknot` prints the cycles of your project with the few imports that go against the layer order.

Did I miss a case where the compiler keeps or drops an import? `importsNotUsedAsValues` and old `preserveValueImports` projects are the ones I am least sure about.


r/typescript • • 3d ago

How do you stop a singleton service from holding per-request state?

0 Upvotes

I've been building a small DI layer for Elysia on Bun, and one bug class I wanted the container to catch is a long-lived service holding onto something that only makes sense for one request, like the current user or a request id. It looks fine with one request at a time and then two concurrent requests start seeing each other's data.

The approach I went with: each class declares its lifetime and its dependencies as static fields, and the graph refuses to build if a singleton depends on a request-scoped provider.

```ts
class RequestAudit {
static readonly lifetime = "request" as const;
}

class ReportService {
// singleton by default
static readonly needs = [RequestAudit] as const; // the graph rejects this
constructor(private readonly audit: RequestAudit) {}
}
```

Routes that need per-request things get them through a handler wrapper instead, so request-scoped objects never end up stored on a singleton.

Curious how others handle this in Node or Bun backends. Do you lean on AsyncLocalStorage, pass a context object around explicitly, or have your container enforce it? And is a hard error too strict for cases where someone actually wants it?

It's alpha (0.1.x), so the API may still change. Docs if anyone wants to look: https://elpod.vercel.app/docs/dependency-injection


r/typescript • • 5d ago

Our workflow runtime is all in typescript and we got asked for a python port. How do you habdle mixed language setup?

4 Upvotes

I work on Workflow Builder, an open source runtime that runs workflows drawn as diagrams on Temporal. It takes a case from the first step to a final and keeps the decisions, versions and the full case record along the way, Retries timeouts, and history come from Temporal.

Under the hood one generic TS workflow walks a JSON graph (the DSL interpreter pattern), every node is an activity. The rest of the runtime is Typescript too: the worker plugin, the store, the API. We just got asked for a python version.
Our plan is to keep runtime in typescript and let nodes run on python workers on their own task queue. The alternative is a second runtime in python and hen two interpreter workflows have to stay replay safe.

I have the following questions for people whose workers are not typescript:

  1. do you already mix languages across your workers?
  2. would one node worker running our workflow be a dealbreaker in your production or just annoying? if dealbreaker, why?
  3. are python activities enough or do you beed the workflow itself in python (agent loops as workflow, timers, signals)? Would a python child workflow called from the TS one cover it?

r/typescript • • 6d ago

Using readonly on a type's field to allow to implement it via a getter?

0 Upvotes

Disclaimer: I got this answer from an AI, which I haven't used before. It doesn't show its sources. I've got no idea if it's a legitimate option or a hallucination.

I asked it how to declare a getter within a type. It gave me the answer and suggested using readonly as an alternative.

I mean, it doesn't make much of a difference, in that it just makes a shorter syntax for when the getter just needs to return a simple variable without doing anything to it.

Is this a valid use?

Would the readonly field be able to be implemented via an actual getter, or does it mean that it could be a function?


r/typescript • • 6d ago

How do you keep feature modules from reaching into each other's internals in a backend?

3 Upvotes

In most backends I've worked on, "modules" are just folders. Nothing stops billing from importing a repository straight out of users, and after a while every feature quietly depends on every other feature's internals.

I'm trying a different approach in Elpod, a small framework I'm building on top of Elysia. It runs on Bun rather than Node, but the problem is the same. Each feature is a plain value that says what it owns and what it exposes:

```ts
export const users = pod({
name: "users",
prefix: "/users",
controller: UsersController,
providers: [UsersService, UsersRepository],
exports: [UsersService],
});

export const billing = pod({
name: "billing",
prefix: "/billing",
controller: BillingController,
imports: [users],
providers: [BillingService],
});
```

And a class lists what it needs as a static tuple, no decorators:

```ts
export class BillingService {
static readonly needs = [UsersService] as const;

constructor(private readonly users: UsersService) {}
}
```

Only what users exports is visible to billing, so UsersRepository stays private. Import cycles between features and duplicate exports fail when the app composes, not later. These are in-process boundaries though, not security boundaries, so authorization still lives in the services.

For those of you with bigger Node services: do you enforce this kind of thing at all? dependency-cruiser, eslint-plugin-boundaries, Nx module boundaries, or just code review? I'm curious whether doing it at the DI level feels useful or like extra ceremony.

It's alpha (0.1.x), so the API can still change. Docs if you want to look: https://elpod.vercel.app/docs/features-and-pods/


r/typescript • • 8d ago

How would you type-check a DI dependency list against the constructor params?

7 Upvotes

I'm building a small DI layer for Elysia on Bun with no decorators. A class lists its dependencies like this:

class Greeter {
  static readonly needs = [Clock] as const;
  constructor(private clock: Clock) {}
}

Right now it only checks at boot that the list length matches the constructor's parameter count. Someone on r/bun pointed out that swapping Clock for a different class with the same arity slips through, and they're right.

My plan is to map needs to instance types and compare that against ConstructorParameters<typeof Greeter>, then add a @ts-expect-error test for the swap. Has anyone done this cleanly without the error messages turning into a wall of generics?

(Project is Elpod, early alpha, if anyone's curious: https://elpod.vercel.app)


r/typescript • • 10d ago

Codex Generated JavaScript and TypeScript Files Can Be Painful To Read. Use Airbnb JavaScript Style Guide.

0 Upvotes

Airbnb JavaScript style guide can significantly make your code better and readable by humans. In my last post I mentioned about setting up Codex Cloud and increasing my output per unit time.


r/typescript • • 12d ago

vercel-labs/scriptc: TypeScript-to-Native Compiler

Thumbnail
github.com
71 Upvotes

Vercel Labs has released scriptc, an experimental Apache 2.0 licensed compiler that turns ordinary TypeScript into small native executables with no Node, V8 and no JavaScript engine in the binary.

The repository was created on 22 July 2026 and has since gathered around 4.9k stars. scriptc uses the real TypeScript compiler for parsing and type checking, lowers programs to a typed IR, then emits readable C, LLVM IR, assembly, objects, native executables or WebAssembly via WASI Preview 1.

Every construct lands in one of three tiers: compiled statically by default, run dynamically inside an embedded quickjs-ng engine of roughly 620KB when --dynamic is passed for npm packages and any typed code, or rejected at compile time with an SC code and a rewrite hint.

A benchmark of scriptc 0.0.16 against Bun 1.3.12 and Node 24.18.0 recorded median CLI startup of 1.78ms versus 21.29ms for Bun and 61.78ms for Node, with idle memory of 1.9MiB for a framework free node:http server. The same tests found Hono required --dynamic, pushing 62% of the server into QuickJS and cutting throughput to 18.4k requests per second against Bun's 70.5k.


r/typescript • • 11d ago

Optique 1.4.0: Default commands, Markdown references, and more focused help

Thumbnail
github.com
2 Upvotes

r/typescript • • 13d ago

Any TypeScript ORM that supports different databases (no raw SQL/query builders this time) at the same time?

10 Upvotes

So, I am building a real estate application in Express for college.

I want to have a PostgreSQL database as the main database and the SQLite database for unit testing. For example, I made a service for the User model and I want to use it both for the web app and testing. I need a TypeScript ORM that supports multiple datasources (PostgreSQL and SQLite (in-memory if possible)). services/UserService.ts:

import { compareSync, hashSync } from "bcrypt";

import logger from "../global/logger";
import logMessages from "../global/logMessages";
import { userMapper as mapper } from "../mappers";
import { User } from "../models";
import { IRegister, IUserChangePassword, IUserUpdate } from "../interfaces";
import prisma from "../prisma/main/client";

export default class UserService {
    constructor(private prisma: any) {}

    // Main
    async create(data: IRegister) {
        delete data.password2;
        data.email = data.email.toLowerCase();
        data.password = hashSync(data.password, 10);

        // 1 Parametrized queries
        const user = await prisma.user.create({ data });

        // 5 Security logging
        logger.info(logMessages.USER_SERV.create, { userId: user.id });
        return mapper.toClass(user);
    }

    // ... other methods
}

I used to use Prisma, but setting it to support both PostgreSQL and SQLite was so convoluted. I had to build a schema, a config and a client for each datasource. That also implied having to duplicate the entire services just for unit testing.

Configurations `prisma/main/prisma,config.ts` and `prisma/test/prisma.config.ts`:
```TS
import "dotenv/config";
import { defineConfig, env } from "prisma/config";

export default defineConfig({
    schema: "./schema.prisma",
    migrations: { path: "./migrations" },
    datasource: { url: env("MAIN_DATABASE_URL") }
});
// same as above

export default defineConfig({
    // same as above
    datasource: { url: env("TEST_DATABASE_URL") }
});

prisma/main/client.ts and prisma/test/client.ts:

import { PrismaPg } from "@prisma/adapter-pg";

import { PrismaClient } from "./generated/client";
import { MAIN_DATABASE_URL } from "../../global/env";

const connectionString = MAIN_DATABASE_URL;

const adapter = new PrismaPg({ connectionString });
const client = new PrismaClient({ adapter });
export default client;

import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";

import { PrismaClient } from "./generated/client";
import { TEST_DATABASE_URL } from "../../global/env";

const connectionString = TEST_DATABASE_URL;

const adapter = new PrismaBetterSqlite3({ url: connectionString });
const client = new PrismaClient({ adapter });

export default client;

So, I turned the service into a class that will accept any client in the constructor.

export default class UserService {
    constructor(private prisma: any) {}

And I instantiated it in controllers/auth.controller.ts and tests/userService.test.ts:

// ... other imports
import { mainClient } from "../prisma";
import { UserService } from "../services";

const service = new UserService(mainClient);
import { testClient } from "../prisma";
import { UserService } from "../services";

const service = new UserService(client);

I tried Drizzle ORM with PGLite, but I did not know how to set it up for both main db and testing.

I need something simple like its in Django and Laravel. Please don't recommend raw SQL and query builders (Kysely (I hate that name) and others) at the moment.


r/typescript • • 14d ago

Seeking feedback on my niche TS code review tool(PRSense)

2 Upvotes

Hi r/typescript!

Long time lurker here. I've been a javascript dev for almost 10 years now, and moved to TypeScript a couple of years ago for serious work. Coming from an OCaml background the logical choice would've been to switch to rescript but somehow I ended up loving TypeScript for its simplicity and elegance, and much needed algebraic types. I did some serious Java coding earlier, so it would appear that I've come full circle, as TS seems like the most compact yet really powerful Java-esque language.
I've used TS in projects small and large, and couldn't go back. As of recently I've been using LLMs to generate a lot of TS code so to accelerate my workflow while maintaining my sanity. To delve deeper into the typescript ecosystem, I built https://github.com/navxio/PRSense and my productivity spiked immediately. Now I can use LLM generated code in my small to medium sized projects without headaches, and at least one of them is live with non trivial revenue(6 months in production). Needless to say it's an indispensable part of my workflow now.

It's a tiny yet powerful command line tool that integrates with git so you can use it with your agents too if you're so inclined. Looking for some devs who still write code by hand (and use LLM generated code). Any feedback is appreciated!

Thanks for reading and cheers!

Edit 1: Grammar Edit 2: It uses ts-morph aggressively to reduce LLM token budget, essentially minimizing the token usage. More on the architecture to follow in a blog post!!


r/typescript • • 15d ago

a ReBAC authorization platform where your permission schema is just TypeScript (open source, MIT)

6 Upvotes

Hey r/typescript 👋

My team and I been working on peretyn, an open-source authorization platform for TypeScript apps. You describe who can do what as relationships between things (users, teams, documents, whatever your app has), and your app asks one question: is this allowed?

A few highlights:

- The schema is plain TypeScript. No separate DSL to learn. Your types and relations are checked at compile time, so a typo in a permission name fails the build instead of failing in prod.

- Built on OpenFGA. It's the same relationship-based model as Google Zanzibar, so roles, sharing, teams and nested access all fit without piling up special cases.

- Self-hosted in one command. One install script brings up the whole stack: Postgres, the runtime, the control plane and a dashboard. There's also a local mode if you just want to poke at it.

- SDK + CLI. Use the SDK in your app and the CLI to ship your schema like any other piece of infrastructure.

- Open source, MIT licensed. Whatever you build on it stays yours.

The landing page is a bit of an experiment too: you walk through it as user:visitor, and each section unlocks as you earn new relations in your own little permission graph. It's probably the quickest way to get the idea, and there's nothing to install.

Feel free to give it a look: https://peretyn.dev

Docs: https://docs.peretyn.dev and GitHub: https://github.com/peretyn/peretyn

Heads up, it's early (pre-1.0), so expect some breaking changes between minor versions. That's exactly why I'd love feedback now: does the approach make sense? Is anything confusing? What would stop you from using it? Roasts welcome too 🙂

Thanks for reading!


r/typescript • • 15d ago

I've spent 3 years on a TypeScript library for generating Excel reports from a typed schema, v5 just shipped

28 Upvotes

Hey r/typescript,

I've been building typed-xlsx for about 3 years now, it's a library for generating Excel reports from TypeScript : https://typed-xlsx.vercel.app

It only writes files, so for reading or editing existing spreadsheets SheetJS or ExcelJS are what you want. But if you have typed data and need to turn it into a structured report, from a 3 column export to a multi-sheet pack with formulas, totals, charts and pivots, I honestly think it's the best option out there.

You describe the columns once, typed against your row type:

type Invoice = {
  id: string;
  customer: { name: string };
  qty: number;
  unitPrice: number;
};

const invoices = createExcelSchema<Invoice>()
  .column("id", { header: "Invoice #", accessor: "id" })
  .column("customer", { header: "Customer", accessor: "customer.name" })
  .column("qty", { header: "Qty", accessor: "qty" })
  .column("price", { header: "Unit price", accessor: "unitPrice" })
  .column("total", {
    header: "Total",
    // written as =(C2*D2) in the file
    formula: ({ refs }) => refs.column("qty").mul(refs.column("price")),
    summary: (s) => [s.formula("sum")],
  })
  .build();

The same schema works for any size of export:

// in memory
const workbook = createWorkbook();
workbook.sheet("Invoices").table("invoices", { rows, schema: invoices });
await workbook.writeToFile("./invoices.xlsx");

// streamed, e.g. 500k rows from a DB cursor
const stream = createWorkbookStream();
const table = await stream
  .sheet("Invoices")
  .table("invoices", { schema: invoices });

for await (const batch of cursor) {
  await table.commit({ rows: batch });
}
await stream.pipeToNode(res);

It's fast: 200k styled rows stream in about 3.5s with memory flat around 275 MiB, roughly 3x faster than v4. Zero dependencies, runs on Node, Bun, Deno and Cloudflare Workers.

Files look clean with no styling at all, and branding is a theme with a few colors. Per-row styles and native Excel conditional formatting are there when you need them.

The types go past accessors: a typo like customer.nam gets a "did you mean", a checkbox column only accepts booleans, a chart's y has to be numeric, and formulas reference columns by id so a wrong id doesn't compile. Formulas are optional, you can also just compute values in TS.

Also in there: native Excel tables, dynamic columns, sub-rows, dropdowns and validation, sheet protection, hyperlinks, images, sparklines and more. The playground has full workbooks for most of it.

It ships an agent skill too (npx skills add ChronicStone/typed-xlsx), and since everything is typed, tsc tells the agent when it got something wrong.

Repo: https://github.com/ChronicStone/typed-xlsx Docs: https://typed-xlsx.vercel.app Playground: https://typed-xlsx.vercel.app/playground

Feedback welcome, especially if you've built Excel exports in TS before.


r/typescript • • 15d ago

Nx monorepo with Node.js + Angular projects

9 Upvotes

We are currently using Nx (v23.x) to manage multiple interdependent projects. The monorepo contains both Node.js packages and Angular applications/libraries.

We still rely on TypeScript v6 and path aliases instead of project references, as Angular does not support them yet.

Is there anyone who's managed to have both TypeScript v7 and v6 on the same Nx monorepo, and correctly build Node.js packages with v7, and Angular applications/libraries with v6? Is this even possible? Note that Angular projects may reference shared libraries (that should be buildable in isolation with TS7 too).

I'm looking for others' experiences as I don't want to find myself on TS6 forever. The status quo is not great honestly.


r/typescript • • 15d ago

trpc-demo-link: Build demos using tRPC client links that mock your API without changing your app/components

Thumbnail
github.com
1 Upvotes

Hi all ! Wanted to share this example repository I made that shows how I build demos using tRPC by minimally mocking routes that are called while viewing the demo (organization).

My TypeScript types are probably cursed but they enforce that newly introduced routes that could break the demo must be mocked. If you you tRPC or have a similarly-shaped SPA this could be useful for you!


r/typescript • • 15d ago

It Depends - TypeScript Debated

0 Upvotes

I wrote this book, and it took me nearly a year to complete. It's about TypeScript practices. It's opinionated, and it's meant to be a little "lighter" to read.

The idea is pretty simple: instead of writing another conventional technical book that tells you what to do, I wanted to build something around debates between developers. Different personalities, different philosophies, different approaches to solving problems. They argue, challenge each other's assumptions, bring working code into the discussion, and sometimes even change their minds.

And here's the thing: not every debate has a clear winner. Sometimes there's a verdict, sometimes the discussion remains open. Because that's how software engineering actually works.

Let me address the question you're probably all thinking right now: Yes, I used AI. Extensively.

However, all the scripts are mine. The voices are mine, the subjects are mine, the debates are mine.

So, what do I mean when I say AI was used extensively?

It helped shape the book and organize its content. It helped with spelling and grammar, refining tones, reviewing the material, making sure all the examples actually work, shaping the chapters themselves, and even helping with the printing process (there's a print version!) and the cover.

I didn't let AI write the text by itself. That was my one rule when working with AI on this book.

The book is free and open source. You don't have to pay a dime to read it. If you prefer a physical copy, there's also a print version available on Amazon, which, for obvious reasons, does cost some money.

Anyway, I'd genuinely love to hear what you think. Whether it's feedback about the content, the format, the opinions, or even the way the book was written.

you can read it here https://eliraz-refael.github.io/it-depends-ts-book/

In there you can find the link to the print version as well.


r/typescript • • 18d ago

getElementById with type guard and variable name guard

13 Upvotes

I've been trying to write a TypeScript wrapper around document.getElementById. I've got something that I'm almost happy with, so I'll start with that, then I'll explain my motivations and you can decide whether this makes sense or not, or which of my assumptions is most wrong.

There's a type guard, which means it will throw an exception if document.getElementById returns an element of the wrong type.

There's also what I'm calling a variable name guard. The wrapper returns an object with a single property with the same name as the html id. This stops the variable name from getting out of sync with the id accidentally - a mistake I seem to be quite prone to, I'm afraid.

Here's the code:

export const getElementById = <K extends string, V extends HTMLElement>(
    elementType: { new (): V },
    id: K,
): Record<K, V> => {
    const elm = document.getElementById(id);

    if (elm instanceof elementType) {
        return { [id]: elm } as Record<K, V>;
    } else if (elm === null) {
        throw new Error(`Element ${id} not found`);
    } else {
        throw new Error(`Element ${id} is of unexpected type, ${elm.nodeName}`);
    }
};

And it's called like this:

import { getElementById } from './getElementById';

const { mmEditor } = getElementById(HTMLTextAreaElement, 'mmEditor');
const { parseButton } = getElementById(HTMLElement, 'parseButton');
const { parseOutput } = getElementById(HTMLElement, 'parseOutput');
const { mmpEditor } = getElementById(HTMLTextAreaElement, 'mmpEditor');
const { unifyButton } = getElementById(HTMLElement, 'unifyButton');
const { unifierOutput } = getElementById(HTMLElement, 'unifierOutput');

When presented with vanilla html DOM code like this, the first question I would always ask is: why haven't I used a web-framework?

In this case, there's a package that I've written, and I wish to demonstrate its use in a web environment. So I'm trying to be inclusive, and write something you can hopefully follow whether your preferred framework is React, Angular, Vue, etc. It being demo code also explains why I wanted nice clearly worded exceptions and then made no effort to catch them.

I have unconsciously excluded JavaScript developers, however. Previously I have written such examples in JavaScript in the hope to include everyone. But this time I automatically chose TypeScript and didn't realize what I'd done until I'd almost finished it. It's 2026, is it OK to exclude JavaScript devs?

The only thing that makes me unhappy about this code is the 'as' statement. You should be able to satisfy yourself that it's correct and the type can't be anything else, but - and this is kind of the point of using a typed language - I'd rather you didn't have to. Unfortunately it's an inference that TypeScript itself doesn't appear to be able to make, and I can't find a way around that.

The elementType which is passed in might be worth elaborating on. I started with one function per element type, and when I combined them, I ended up with this, which would be nice if it would compile

const getElementId = <T extends HTMLElement>(id: keyof Record<string, T>) => {
    const elm = document.getElementById(String(id));
    if (elm instanceof T) {
        return { [id]: elm } as Record<string, T>;
    } else {
        throw new Error(`Element ${id} not found or wrong type`);
    }
}

src/index.ts:23:24 - error TS2693: 'T' only refers to a type, but is being used as a value here.

But it's hobbled by the need to transpile into JavaScript and can't take the type with it. So we pass the elementType in instead, which is defined as an object which has a constructor returning the expected element type. That we can do an instanceof on.

Thanks for reading. It's been nice to have a small piece of code with an easily understood purpose to talk about. That doesn't happen very often. When I start writing a program I'm happy to put any old runtime type check in, just to pander to the compiler's whims, but here I've finished up with something that does make it easy to hack around with a piece of code because it tells me clearly when I inevitably screw up. Anything with a generic in it is always a fun puzzle, I find, and I mean that both in a good and a bad way. I hope you found this interesting, what do you think?


r/typescript • • 18d ago

What happens when a side project you abandoned years ago suddenly becomes relevant again?

0 Upvotes

A few years ago, when Deno was first announced, I started building a NestJS-style framework that could run on both Node.js and Deno.

Like many side projects, it eventually ended up collecting dust.

But the JavaScript ecosystem kept evolving. New runtimes and environments emerged, like Bun and Edge runtimes, and I realized the original idea was more relevant than ever.

So I dusted off the code, rethought a few things, and brought the project back to life.

Today, I'm releasing the first public beta of CHO (which, somewhat amusingly, is already at version 3!) to gather feedback from the community.

CHO runs on every JavaScript/TypeScript runtime, uses native JavaScript decorators instead of TypeScript's legacy decorators, and has zero dependencies.

It's still early days, and I'd love to hear what you think, especially from developers interested in framework design and modern JavaScript.

🦋 https://github.com/cho-js/cho


r/typescript • • 19d ago

Surprising type of a filtered array

8 Upvotes

I have an array that contains a mix of number and string values, in other words its type is (string | number)[]:

a = [0, 1, 2, NaN, 'x']

I wanted to filter only the numeric values 0, 1 and 2 that are not NaN, so I used a perfectly ordinary filter() call:

numbers = a.filter(n => typeof n === 'number' && !isNaN(n))

However, to my surprise the array "numbers" still has type (string | number)[], which logically makes no sense. No string value can pass the filter.

However, if I split the "and" expression to two separate filter() calls the array does get type number[]:

numbers = a.filter(n => typeof n === 'number').filter(n => !isNaN(n))

What's the reason for this surprising behaviour? Is there a general TypeScript principle that applies here?

I'm experienced in JavaScript, however not super well-versed in TypeScript.


r/typescript • • 18d ago

A package for standardizing logging? Looking for thoughts

0 Upvotes

Hey!

How do you guys currently approach event logging?

After reading https://loggingsucks.com/ (like about a year ago), I thought of creating a small TypeScript package where you define a logger with a specific expected output log format, then the tool is used to add context/data during an event/request and finally the tool writes one structured log at the end checking for missing fields.
I've never actually did it, because I doubted that it'd be useful. I also heard pinojs has more or less something like this, but without any actual validation. However, recently I've quickly wrapped up a PoC tool.

The tool (LogPal): https://pages.doteric.net/logpal/ (Of course a lot of it is "vibe code", but it's just a PoC)

It’s a proof of concept for now. If the idea seems useful, I can definitely put the work into making it production ready. I wanted something that you don't have to do almost any configuration, you can just use it out of the box and if really needed then add some extra configuration.

Do you think it's worth investing into such tool? Or it'll become yet another logging tool like various different ones (pino, evlog, winston etc.)? Would you use something like this, or is it better handled within each project separately?


r/typescript • • 19d ago

Refactoring my vibecoded TS repo

0 Upvotes

TLDR: refactoring my codebase feature wise and wsnt to make sure this time it doesn't spiral out like the slop we did with claude in the last 6 months.

Stack: TS Express Prisma and Psql

So, I work as an SDE1 at a startup. Honestly, things got super messy around here because our managers just kept pushing for new features every single day. I finally decided I had to stretch out this project timeline. I am using this extra time to completely clean up my code and move it to a way more maintainable structure. I am ditching our messy, sort-of layered architecture and switching over to a vertical slicing setup. I am also adding clear readme files for every single module, putting up Pino for proper logging, and setting up the actual test suites we need.

This is what I want to ask the community, how can I make sure this migration hits all the right software development best practices? I really want to set things up so that Claude does not mess up my codebase ever again. Any Repo references or stack