r/typescript 1d ago

Creating a function that returns a different class instance based on the argument passed to the function

6 Upvotes

r/typescript 1d ago

What TypeScript patterns actually paid off for me in a project

Thumbnail antonyjones.org
65 Upvotes

I've been using TypeScript professionally for several years, and recently wrote up some lessons learned from a long-running React/Firebase side project.

The article covers the TypeScript patterns that paid off most for me, along with a few mistakes I'd try and avoid making again. These aren't intended as universal rules, just approaches that worked well for this particular project and the problems I was solving.

This is one of my first longer technical articles, so I'd appreciate feedback on the writing itself. Were the explanations clear? Did the examples communicate the ideas well? Is there anything I could improve for future articles?


r/typescript 1d ago

Optique 1.2.0: fluent modifiers, deferred values, new integrations, and a redesigned site

Thumbnail
github.com
5 Upvotes

r/typescript 3d ago

Typed and validated config for decoupled TS codebases

Thumbnail
envapt.materwelon.dev
13 Upvotes

r/typescript 3d ago

Learning typescript as a beginner

15 Upvotes

what are good resources for learning typescript? Im coming from c/cpp and from what ive seen online, I'm not sure if i should go into javascript first or straight into typescript. Additionally not sure what good resources are out there to help me go in the right path. Any recommendations would be greatly appreciated!


r/typescript 4d ago

Type-optimization skill or docs somewhere?

0 Upvotes

Hi all, I'm writing a library with complex type mappings, I'm optimizing TS types based on `instantiations` metric of `tsc --extendedDiagnostics`.

Lately I tried asking AI to refactor types to improve the metric, and that's a super hard task both for me and for AI. Idea: whenever it finds some trick that helped, let it store it to the skill for a later use!

Do anybody have or know about such a "type-optimizer" skill or some kind of docs with a list of techniques for TS type-checker performance? (I know the official TS docs have a few basic recommendations for the types perf)

TS 7 kinda makes this irrelevant, but still, there can be cases when super complex types are still time-consuming even there. Think of giant codebases that use zod inferrence a lot (for example).


r/typescript 4d ago

Bulletproofing User Sync: Handling Clerk and Auth0 Webhook Failures

0 Upvotes

If you're building a web application today, chances are you aren't writing your own authentication system. Managed identity providers like Clerk, Auth0, and Kinde have become the default choice, offering out-of-the-box support for passkeys, multi-factor authentication, and enterprise SSO. That convenience introduces a distributed-systems problem, though: data synchronization. When a user creates an account on a managed auth provider, that system has to notify your primary application database so you can create a matching user record. Please read the complete article here - https://instawebhook.com/blog/bulletproofing-user-sync-handling-clerk-and-auth0-webhook-failures

This happens through webhooks. But what happens if your server is down, your serverless function cold-starts and times out, or your database is momentarily locked when that webhook arrives? A user successfully signs up with your auth provider, but your application has no idea they exist. That breaks the very first login experience, and it's how phantom accounts, broken onboarding flows, and frustrated users happen.

This guide walks through the anatomy of webhook-driven auth architecture, current Auth0 and Clerk webhook practices, and how a resilience layer — using InstaWebhook as a worked example — closes the gap that idempotency and signature verification alone can't.


r/typescript 6d ago

P2P file sharing app without cloud storage, free and open-source

2 Upvotes

Hey,

Few weeks ago I release my open source app called Altersend, it is P2P file sharing tool where you can send files directly between devices over the internet.

When I started developing this tool my main idea was to have solution where I can send files to anyone not just on local network and not be depending on cloud solution.

From technical P2P side everything you send is E2E encrypted via Noise protocol, peers find each other via DHT (think of it as some sort of book with contacts about other peers, and underneath it is Kademlia DHT). So when you want to send file we generate a random key which you should give to another peer. And after this anyone who has that key can connect and download directly from you.

As the initial entry point for peers, public bootstrap nodes are used (we do not host them) and after that peers discover one another through the DHT. Only if you are behind symmetric CGNAT or a VPN we use a blind relay server to help you connect, but the bytes flowing through are encrypted, and you can also disable relay in the settings.

But there are some limitations, like you should keep your phone / laptop opened during the transfer.

Desktop is build with Electron, P2P worker is running using Bare and mobile uses Expo.

Github: https://github.com/denislupookov/altersend

Let me know what do you think about it !


r/typescript 6d ago

Can't read much code, so I make my agents pass tiny JSON checks

0 Upvotes

Can't read much code, but I still need to know when my agents are about to break something.

so I started writing tiny JSON schemas for each step.

lead enrichment has to return company, industry, employee_count. if employee_count comes back as 42 instead of 42, nope.

retrieval has to return source_doc, confidence, snippet. if confidence comes back as 1.3, also nope.

not fancy. just a tripwire.

when I tweak an agent, I keep it in draft, rerun the same inputs, check the schemas, then publish. Enter makes that loop pretty painless because draft and published stay seperate and rollback is there if I mess up.

long multi-step chains are still annoying though. one schema per step is easy. making the whole chain behave is where I still get humbled.


r/typescript 7d ago

Inconsistency with circular references?

5 Upvotes

So, I'm building this Mafia/Werewolf kind of game, I created this registry of the available roles, and then I extracted the type RoleId to be exactly a union of the ids that are present in the object

export const ROLE_REGISTRY = {
  [VillagerRole.id]: {
    roleClass: VillagerRole,
    name: 'Villager',
    iconName: 'villager',
    team: VillagerRole.team.name,
    category: 'base',
    tags: ['idle'],
    description:
      "You have no special power. At day you may discuss with the other villagers to vote out who you think it's the werewolf.",
    max: Infinity,
  },

  ...

}  as const satisfies Record<string, RoleMetadata>

export type RoleId = keyof typeof ROLE_REGISTRY;

Now yes, defining the ids directly in the classes and then using them like that to index the registry was definitely a questionable choice, but besides that, why am I able then to use that exact definition of RoleId in the Role class itself? (which is the parent class for each of the roles)

export abstract class Role {
  static id: RoleId;
  static team: Team;
  abstract seenAsGood: boolean;
  canBeKilledByWolves = true;

  get id(): RoleId {
    return (this.constructor as typeof Role).id;
  }

  ...
}

Typescript sees no problem with that, no circular dependency, which I found weird. So I tried do this once more, this time with the actions that the roles can perform

export const ACTION_REGISTRY = {
  [AttackAction.id]: { actionClass: AttackAction },
  [CheckAction.id]: { actionClass: CheckAction },
  ...
} as const satisfies Record<string, ActionMetadata>;

export type ActionId = keyof typeof ACTION_REGISTRY;

export interface Action {
  readonly id: ActionId;
  ...
}


export abstract class InstantAction<T extends ActionResult> implements Action {
  static id: ActionId;
  
  get id() {
    return (this.constructor as typeof InstantAction).id;
  }

  ...
}


export abstract class ScheduledAction implements Action {
  static id: ActionId;

  get id() {
    return (this.constructor as typeof ScheduledAction).id;
  }

  ...
}

Here TypeScript tells me (as expected) that ActionId is circularly referencing itself. I really don't understand the difference between these two cases, and/or if there is something else entirely that I'm missing that it's the root cause of the problem. I will paste this other piece of code which MAY be relevant.

export abstract class ActiveRole extends Role {
  abstract actions: ActionGroup[];


  canCreateAction(actionId: ActionId): boolean {
    const action = this.findAction(actionId);
    return action.amount > 0;
  }


  protected consumeAction(actionId: ActionId) {
    const action = this.findAction(actionId);
    action.amount--;
  }


  private findAction(actionId: ActionId) {
    const actionGroup = this.actions.find(
      (actionGroup) => actionGroup.options[actionId] !== undefined
    );

    if (!actionGroup) {
      throw new Error('Impossible to find action ' + actionId);
    }

    return actionGroup.options[actionId];
  }

  createAction(
    state: GameState,
    actionId: ActionId,
    source: Player,
    targets: Player[],
    payload?: any
  ): Action {
    const action = this.findAction(actionId);

    this.consumeAction(actionId);

    return action.create(state, source, targets, payload);
  }
}

Thanks in advance


r/typescript 7d ago

Typescript spread operator being used to defy types

33 Upvotes

Hi y'all,

In my team's code I often have this situation. A type is defined:

type Car = {
make: string;
model: string;
}

Then people just add properties with the spread operator:

const car: Car = {
make: 'Toyota',
model: 'Camry',
...{ year: 2000 }
}

Types are basically being ignored. What can I do about this?


r/typescript 12d ago

Is this typescript bug? This can lead to serious problems.

0 Upvotes

```ts let value: "not-supported" | boolean = "not-supported"

if (value === null) { // This should be highlighted as error, but it's not! }

if (value === undefined) { // This also! } ```

This problem occurs even if strictNullChecks is set to true. Typescript version is 6.0.3.

You can try for yourself at official typescript playground: https://www.typescriptlang.org/play/

Am I missing something? Or this is bug?

In my code, this unhighlighted error can lead to some serious problems.


r/typescript 12d ago

node_modules problems

0 Upvotes

Running into an unexpected type error that I've never seen before with some unfortunately structured Google NPM libs. Should be easy to work around this issue with `as` or something similar but I'm curious if anyone has any ideas for a "cleaner" approach (that doesn't involve joining Google to fix their libraries).

The type error is this:

Type 'OAuth2Client' is not assignable to type 'string | GoogleAuth<AuthClient> | OAuth2Client | BaseExternalAccountClient | undefined'.

Type 'import("/Users/me/path/to/project/node_modules/google-auth-library/build/src/auth/oauth2client").OAuth2Client' is not assignable to type 'import("/Users/me/path/to/project/node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/oauth2client").OAuth2Client'.

Types have separate declarations of a private property 'redirectUri'.ts(2322)

Typescript is correct to call this out, but I don't see any way around it that doesn't involve type assertion.


r/typescript 12d ago

TypeScript v7 ToolChain TTSC: plugin for typia, AI codegraph reducing 90% tokens, compiler integrated Lint, unplugin for vite/rollup/etc.

Thumbnail
github.com
0 Upvotes

r/typescript 14d ago

Announcing TypeScript 7.0

Thumbnail
devblogs.microsoft.com
588 Upvotes

r/typescript 15d ago

OpenHarness: typed building blocks for agent runtimes on top of AI SDK 5

0 Upvotes

I built OpenHarness as an open-source TypeScript SDK for people who want to build agent runtimes in code rather than wrap an existing CLI app.

The TypeScript-specific goal is to make the agent loop, session state, tools, provider boundaries, middleware, and UI streaming feel like typed app primitives.

Minimal shape:

```ts import { Agent, createFsTools, createBashTool, NodeFsProvider, NodeShellProvider, } from "@openharness/core"; import { openai } from "@ai-sdk/openai";

const agent = new Agent({ name: "dev", model: openai("gpt-5.4"), tools: { ...createFsTools(new NodeFsProvider()), ...createBashTool(new NodeShellProvider()), }, maxSteps: 20, });

for await (const event of agent.run([], "Refactor the auth module")) { if (event.type === "text.delta") process.stdout.write(event.text); } ```

Current pieces include:

  • Agent and Session primitives
  • composable middleware for retry, compaction, persistence, hooks, and turn tracking
  • MCP server support, skills, AGENTS.md-style instructions, and subagents
  • React/Vue helpers for AI SDK 5 streaming UIs
  • experimental ChatGPT/Codex OAuth provider

Repo: https://github.com/MaxGfeller/open-harness Docs: https://docs.open-harness.dev Package: https://www.npmjs.com/package/@openharness/core

I'm especially looking for TypeScript API feedback: do the async generator event streams and middleware composition feel idiomatic, or would you expect a different shape for embedding agents in TS apps?


r/typescript 17d ago

I'm going insane on how to rigorously structure my monorepo (backend + frontend)

22 Upvotes

TL;DR: Is there already a good framework/starter-kit for designing good maintainable frontend/backend monorepos? I'm not talking about bundlers like turborepo or NX, neither I'm talking about t3-stack or better-t-stack, I'm talking more of a very strict paradigm to design typescript frontend/backend monorepos.

I am currently slowly migrating a vibe-coded prototype of a huge software (20+ domains) to an actual production-ready product and I'm noticing how I'm slowly starting to hate the freedom TS/JS gives you, the fact that you can shape your codebase how you wish, the first refactoring I did was migrating all those scattered small sloppy ts files to domain services/sub-services, providing strong hiearchy (Java/C# like), but then noticed that I wasn't leveraging monorepo's features the fullest, so I had to modularize everything, but here I don't know what to do anymore, I don't think I was the only one facing this issue, and I can't migrate to another language 'cause we just can't afford it. The architecture I've thought of was to divide domains in packages and make packages have a strict structure both folder-wise and code-wise:

@acme/foo/ ├── app/ │ ├── services/ │ │ └── foo/ │ │ ├── index.ts │ │ └── types.ts │ └── routers/ │ └── index.ts ├── data/ │ ├── models/ │ │ └── index.ts │ └── index.ts └── web/ ├── components/ │ ├── Foo.svelte │ └── Bar.svelte └── index.ts

But I feel I'm reinventing something someone must have already figured out, but I don't know where to search anymore...


r/typescript 17d ago

Distributive Conditional Types

Thumbnail tejasbubane.github.io
30 Upvotes

I started digging into TypeScript's type system for fun and stumbled onto distributive conditional types. One of those quiet features that is confusing until it clicks.


r/typescript 17d ago

Am I missing any security issues in this browser-to-PostgreSQL architecture?

0 Upvotes

Hi everyone,

I'm specifically looking for feedback from senior backend, infrastructure, and security engineers.

I'm building a browser-based PostgreSQL IDE called Schema Weaver. The main problem I'm trying to solve is that browser applications shouldn't have PostgreSQL credentials, while users' databases may be running on localhost, inside private VPCs, corporate networks, or cloud providers like AWS, Supabase, and Neon.

Instead of exposing the database or asking users to deploy their own backend, I built a small TypeScript/Node.js connector called sw-agent.

Current architecture:

Browser

│ WSS

Cloud Relay

│ Outbound WSS

SW Agent

PostgreSQL

The idea is:

- The agent runs wherever PostgreSQL is reachable.

- The browser never receives PostgreSQL credentials.

- The agent owns the credentials and executes queries locally.

- The agent only makes outbound connections (no inbound ports or public IP required).

- The relay only routes traffic between the browser and the agent.

- The agent performs permission checks and SQL validation before execution, with local hash-chained audit logs for every action.

I'm looking for honest technical feedback before I continue building this further.

Some questions I have:

- Am I missing any obvious security vulnerabilities or attack surfaces?

- Is the trust model reasonable?

- Would you design the networking or authentication differently?

- Are there better-established patterns for solving this browser ↔ private database problem?

- If you were reviewing this architecture in your company, what concerns would you raise?

Resources if you'd like to review it:

Architecture Blog:

https://vivekmind.com/blog/sw-agent-bridge-agent-that-connects-schema-weaver-browser-ide-to-user-s-postgresql-databases

GitHub:

https://github.com/Schema-Weaver/sw-agent

npm:

https://www.npmjs.com/package/@vivekmind/sw-agent

I'm genuinely looking for criticism and suggestions, not promotion. I'd appreciate any feedback on the architecture, implementation, or security model.


r/typescript 18d ago

Zenolith a renderer engine

5 Upvotes

Hi everyone, a while ago I posted about zenolith, Now I've been changing the direction of it. It's no longer a diagram library, it's now intended to be a renderer engine.

It currently has basic support of 7 diagrams, diagram support may vary depending on syntax: mermaid, plantuml and zenolith own syntax.

I would like if you give it a look. It has a playground so no downloads required. I would appreciate any feedback.

It will be open-source once it's out of beta, since I'm still fleshing things out and want it to be in a "good" state for contributors, or interested people.

https://miguelarmendariz.github.io/zenolith/


r/typescript 18d ago

TS Compiler Graph, 10x fewer tokens in Claude Code and Codex, by TypeScript-Go toolchain

Thumbnail
github.com
0 Upvotes

r/typescript 20d ago

Pairing for typescript backend interview

2 Upvotes

Hey folks,

I have an interview coming up for a backend developer role, with the tech stack used: Node, Express/Nest.js, TypeScript & SQL.

Is anyone ready for pairing on coder pad or HackerRank? Let me know.

Right now I am mostly writing the solo programs for service, etc., but wanted to get into real-world queries.

We can start after the July 4th weekend.

Appreciate if anyone can spare sometime 😊

Thanks a lot


r/typescript 20d ago

A question about typescript games

8 Upvotes

I am a fairly new typescript developer, I've got a lot of experience in other environments and languages, so as a side project I had decided to try my hand using typescript since I have gotten used to strong typed languages. Anyway my question is this how many of you make games and is there a real path to do so? I'm pretty burnt out on unity and godot is just hard to use (for me) and unreal is just not useful for the games I like making. I like old school flash games or retro styled games and typically stick to platformers, arcade/puzzle games or rogue like/ lite rpgs.


r/typescript 21d ago

Heads up, watch out what you click when you search tsx package related stuff

30 Upvotes

Try doing a google search for tsx package. Their legit website is https://tsx.hirok.io/, but you will most likely see https://tsx.is in search results which seems like a weird (potentially malicious?) website impersonating tsx.

I clicked it once out of empty-mindedness (I was going fast and it was one of the very first few results) and it displayed a plain white page and indicated it is "loading" something - I closed it as soon as the realization hit me.

Anyone saw this website before and knows whether it's malicious or not? Def looks like one


r/typescript 21d ago

Barnsley Fern fractal - click to zoom

Thumbnail
slicker.me
2 Upvotes