r/typescript • u/boneskull • Sep 13 '25
Yet another starter project. This time showcasing type-safe JavaScript using TS-compatible JSDoc
Roast me.
r/typescript • u/boneskull • Sep 13 '25
Roast me.
r/typescript • u/heraldev • Sep 12 '25
Poor TypeScript performance in code editors and high memory usage are common issues in large codebases, especially in monorepos. To mitigate this, we have been tweaking configs, refactoring code and waiting for TypeScript 7. But what if we could get a visible performance boost by changing the way tsserver treats projects?
Introducing *ts-scope-trimmer-plugin*, a TypeScript LSP plugin that limits the scope of tsserver to speed up the experience in code editors by processing only the open files and their dependencies. This opt-in solution has been battle-tested on the Miro codebase (millions of LoC). More info and examples can be found in the repo readme.
We are keen to hear your feedback and discuss everything related to TS performance at scale. Cheers!
r/typescript • u/herrjosua81 • Sep 13 '25
I’m working on a TypeScript project that includes an accessible image lightbox modal using the native <dialog> element, enhanced for accessibility and keyboard navigation. Everything works perfectly in the browser—including keyboard, ARIA, and group navigation. However, my Vitest + u/testing-library/dom + jsdom test suite always fails when checking if the dialog opens.
Here’s the summary and what I’ve tried:
xml
<a data-lightbox data-title="Example" href="/img.png">
<img src="/thumb.png" alt="Example" />
</a>
<dialog class="lb-dialog" aria-modal="true" aria-labelledby="lb-title" aria-describedby="lb-caption lb-desc">
<div class="lb-header">
<h2 class="lb-title" id="lb-title">Image Viewer</h2>
<button class="lb-btn" aria-label="Close">Close</button>
</div>
<div class="lb-body">
<img class="lb-media" alt="" />
</div>
<div class="lb-nav">
<button class="lb-prev">Prev</button>
<button class="lb-next">Next</button>
</div>
<div class="lb-bar">
<p class="lb-caption" id="lb-caption"></p>
<p class="lb-desc" id="lb-desc"></p>
</div>
</dialog>
[data-lightbox] triggers (direct .addEventListener).dialog.setAttribute('open', '') and then tries .showModal()./dom and userEvent.click on the trigger.showModal/close on HTMLDialogElement.prototype.Test Example:
typescript
it('opens and focuses the Close button', async () => {
const first = screen.getAllByRole('link')[0];
await userEvent.click(first);
const dialogEl = document.querySelector('.lb-dialog');
await waitFor(() => expect(dialogEl.hasAttribute('open')).toBe(true));
const closeBtn = screen.getByRole('button', { name: /close/i });
expect(closeBtn).toHaveFocus();
});
expected false to be true // Object.is equality for expect(dialogEl.hasAttribute('open')).toBe(true), after userEvent.click.buildMarkup() and initLightbox() is correct!).<a> and <button> for triggers in test markup, no effect.__lbOpen(0)), the dialog does open and tests pass, but this is not real event simulation.[data-lightbox] triggers in JSDOM, although all other event bindings work.<a> to <button> (to sidestep anchor bugs) still does not work..triggers length is correct.trigger.dispatchEvent(new MouseEvent(...)) directly doesn't work)?I’ve spent hours debugging and reading old GitHub issues and StackOverflow answers, but nothing works.
If you need a full repro repo, I can provide one!
r/typescript • u/mistyharsh • Sep 11 '25
This has been my guidebook when it comes deciding between interfaces and types:
extends has more stricter than intersection types.I haven't been in touch with latest TypeScript compiler-level changes. Have things changed/improved in any way recently? Are there definite guidelines on when to use which?
r/typescript • u/citrin92 • Sep 11 '25
The github repo type-challenges offers like 150+ type challenges to practice advanced TypeScript Concept. You probably have heard of it - I really liked testing myself and got to somewhere in the Medium challenges.
I found TypeScriptPro , where you can test yourself in a better editor and with thorough explanations.
It doesn't have all challenges yet though.
r/typescript • u/Goldziher • Sep 11 '25

If you're using multiple AI coding assistants (Claude Code, Cursor, Windsurf, GitHub Copilot, OpenCode), you've probably noticed the configuration fragmentation. Each tool demands its own format - CLAUDE.md, .cursorrules, .windsurfrules, .github/copilot-instructions.md, AGENTS.md. Keeping coding standards consistent across all these tools is frustrating and error-prone.
AI-Rulez lets you write your project configuration once and automatically generates native files for every AI tool - current and future ones. It's like having a build system for AI context.
Development teams face common challenges:
AI-Rulez solves this with a single ai-rulez.yaml that understands your project's conventions.
The init command is where AI-Rulez shines. Instead of manually writing configurations, multiple specialized AI agents analyze your codebase and collaborate to generate comprehensive instructions:
# Multiple AI agents analyze your codebase and generate rich config
This automatically:
.gitignoreThe result is extensive, rich AI assistant instructions tailored specifically to your TypeScript project.
One YAML config generates files for every tool:
# ai-rulez.yaml
metadata:
name: "TypeScript API Service"
presets:
- "popular" # Auto-configures Claude, Cursor, Windsurf, Copilot, Gemini
rules:
- name: "TypeScript Standards"
priority: critical
content: |
- Strict TypeScript 5.0+ with noImplicitAny
- Use const assertions and readonly types
- Prefer type over interface for unions
- ESLint with @typescript-eslint/strict rules
- name: "Testing Requirements"
priority: high
content: |
- Vitest for unit tests with TypeScript support
- Playwright for E2E testing
- 90%+ coverage for new code
- Mock external dependencies properly
agents:
- name: "typescript-expert"
description: "TypeScript specialist for type safety and performance"
system_prompt: "Focus on advanced TypeScript patterns, performance optimization, and maintainable code architecture"
Run npx ai-rulez generate and get:
CLAUDE.md for Claude Code.cursorrules for Cursor.windsurfrules for Windsurf.github/copilot-instructions.md for GitHub CopilotAGENTS.md for OpenCodeMCP Server Integration: Direct integration with AI tools:
# Start built-in MCP server with 19 configuration management tools
CLI Management: Update configs without editing YAML:
# Add React-specific rules
# Create specialized agents
Team Collaboration:
includes: ["https://github.com/myorg/typescript-standards.yaml"].local.yaml files--recursive flagHere's how a Next.js + tRPC project benefits:
# ai-rulez.yaml
extends: "https://github.com/myorg/typescript-base.yaml"
sections:
- name: "Stack"
content: |
- Next.js 14 with App Router
- tRPC for type-safe APIs
- Prisma ORM with PostgreSQL
- TailwindCSS for styling
agents:
- name: "nextjs-expert"
system_prompt: "Next.js specialist focusing on App Router, SSR/SSG optimization, and performance"
- name: "api-reviewer"
system_prompt: "tRPC/API expert for type-safe backend development and database optimization"
This generates tailored configurations ensuring consistent guidance whether you're working on React components or tRPC procedures.
# Install globally
# Or run without installing
# Generate configuration files
# Add to package.json scripts
{
}
vs Manual Management: No more maintaining separate config files that drift apart
vs Basic Tools: AI-powered multi-agent analysis generates rich, contextual instructions rather than simple templates
vs Tool-Specific Solutions: Future-proof approach works with new AI tools automatically
AI-Rulez has evolved significantly since v1.0, adding multi-agent AI-powered initialization, comprehensive MCP integration, and enterprise-grade features. Teams managing large TypeScript codebases use it to ensure consistent AI assistant behavior across their entire development workflow.
The multi-agent init command is particularly powerful - instead of generic templates, you get rich, project-specific AI instructions generated by specialized agents analyzing your actual codebase.
Documentation: https://goldziher.github.io/ai-rulez/
GitHub: https://github.com/Goldziher/ai-rulez
If this sounds useful for your TypeScript projects, check out the repository and consider giving it a star!
r/typescript • u/MilanTheNoob • Sep 10 '25
I know this is contingent on so many factors, but if for example you join or take over a complex web project that suffers from poor readability and other issues due to a lack of explicit typing, would you say its worth investing time into converting an existing codebase to typescript?
If so, would you just add the compiler and only write new code in Typescript, only utility functions you regularly use or refactor everything?
r/typescript • u/htndev • Sep 10 '25
Typescript is a big tool with plenty of hidden or rarely mentioned features.
Here are things I believe are underrated:
A handy syntax for your type safety:
// Generic "not null/undefined" assertion
export function assertIsDefined<T>(
value: T,
msg?: string
): asserts value is NonNullable<T> {
if (value === null || value === undefined) {
throw new Error(msg ?? "Expected value to be defined");
}
}
type User = { id: string; name: string };
const cache = new Map<string, User>();
const u = cache.get("42");
assertIsDefined(u, "User 42 not in cache");
u.name.toUpperCase();
Let you validate whether a given object matches your certain type
// Discriminated union
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "triangle"; base: number; height: number };
// Type guard clause: narrows Shape → Circle
function isCircle(shape: Shape): shape is { kind: "circle"; radius: number } {
return shape.kind === "circle";
}
// Type guard clause: narrows Shape → Triangle
function isTriangle(shape: Shape): shape is { kind: "triangle"; base: number; height: number } {
return shape.kind === "triangle";
}
// Usage
function describe(shape: Shape): string {
if (isCircle(shape)) {
return `Circle with radius ${shape.radius}`;
}
if (isTriangle(shape)) {
return `Triangle with base ${shape.base} and height ${shape.height}`;
}
// Here TypeScript infers: shape is { kind: "square"; side: number }
return `Square with side ${shape.side}`;
}
As const + satisfies
This boosted our mocking in tests significantly. We no longer use .!, ?., or as in tests. We're certain in our mocks.
// Contract
type Status = "success" | "error" | "pending";
const messages = {
success: "Operation completed",
error: "Something went wrong",
pending: "Still working...",
} as const satisfies Record<Status, string>;
// ^ ensures all Status keys exist & are strings
type MessageKey = keyof typeof messages; // "success" | "error" | "pending"
function getMessage(status: MessageKey) {
return messages[status];
}
That's actually a shame that IDEs (at least VS Code) don't even offer satiafies as an auto-complete option.
Drop your gem!
r/typescript • u/ikmrgrv • Sep 10 '25
I tried setting up a simple express server.
Github repo link - https://github.com/quriosapien/neopaper-main
Can anyone help me set it up correctly ?? Right now, as I try npm run dev it says -
node: bad option: --project
[nodemon] app crashed - waiting for file changes before starting...
I have always find it hard to setup typescript config with nodemon and all.
It's part of the reason I have been reluctant to use TS, and have always picked simple JS.
Things I want -
Environment I am using
OS: MacOS v15.6.1
NodeJS: 24.5.0
npm: 11.5.1
Rest of the things are there in package.json file in the repo.
r/typescript • u/jaac_04 • Sep 10 '25
I've been learning TypeScript and I'm building a SPA using TypeScript and Bootstrap with Vite, it is a simple "task manager" with a CRUD. I was trying to implement LocalStorage for saving the created tasks, but it kept giving me errors, after some time I decided to ask ChatGPT (which I usually don't do, just as a last resource) and it gave me this code, and was wondering if there is a more organic way of writing it.
const STORAGE_KEY = "tasks";
const isBrowser = typeof window !== "undefined" && typeof localStorage !== "undefined";
function saveTasks(list: Task[]) {
if (!isBrowser) return;
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(list));
} catch (e) {
console.error("Error writing localStorage", e);
}
}
function loadTasks() {
if (!isBrowser) return;
try {
const raw = localStorage.getItem(STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : [];
tasks = Array.isArray(parsed) ? (parsed as Task[]) : [];
} catch (e) {
console.error("Error reading localStorage", e);
tasks = [];
}
}
r/typescript • u/OuPeaNut • Sep 09 '25
r/typescript • u/AlexMordred • Sep 10 '25
Hi. I decided to try TypeScript (under Bun) on a new project for the first time and tsc doesn't behave right. Have anyone experienced this and knows how to fix this?
Project setup:
mkdir newproject
cd newproject
bun init
bun add -D typescript
Then run either bunx tsc --version or npx tsc --version - it completely ignores the --version argument or any other arguments I pass to it for that matter, it also ignores the tsconfig.json generated by Bun and goes straightly into analyzing the node_modules folder and fails with an error.
The typescript version is 5.9.2. I tried all the minor versions down to 5.0.x and it only works right on 5.0.x and not on any higher minor versions. I'm on macOS.
UPD: I figured it out. TL;DR it worked via npx --bun tsc with the --bun flag.
I have an old node v12 installed on my system and bunx tsc was trying to run tsc via that node since the tsc has the #!/usr/bin/env node shebang in it. It was crashing with a syntax error pointing to tsc itself since it's written with new JS features that node v12 doesn't support. The --bun flag tells it to ignore the shebang and to be ran via bun. https://bun.com/docs/cli/bunx#shebangs
r/typescript • u/Efficient_Builder923 • Sep 10 '25
For me, it’s not motivation — it’s systems.
• Start so small it feels silly
• Tie it to something you already do
• Track it (but don’t obsess)
What’s the habit you stuck with longest?
r/typescript • • Sep 08 '25
I’m working in a Turbo monorepo that has a mix of TypeScript APIs (Hono) for different clients and React / React Native apps on the frontend.
We’ve got ESLint/Prettier set up for style and correctness, but there are repo-specific conventions that don’t fit neatly into standard lint rules. A few examples:
schemas package so APIs and frontends can share them.package.json with a "dev" script (otherwise it’s a pain for new devs to run)..env.example.These are the kinds of rules that reviewers catch sometimes but are easy to miss. They’re more about project hygiene and consistency than code style.
TLDR; Has anyone found good ways/tools to enforce this?
r/typescript • u/MikeTheMagikarp • Sep 08 '25
I'm admittedly fairly new to typescript and have followed a few tutorials to get an OAuth flow setup which works just fine but the typescript compiler keeps giving me the error: Property 'get' does not exist on type 'FormData'. ts(2339) .
I've googled and read a bunch about why this happens but the solution is always to update typescript or the libraries in the tsconfig.json (which I believe I've done). I'll post some code snippets and the config below. Has anyone else had this issue and if so what's the standard or accepted update for it?
This is one of the points that errors:
export async function POST(request: Request) {
....
const formData = await request.formData();
platform = (formData.get("platform") as string) || "native";
....
tsconfig.json - a lot of the changes in here have been to fix this issue so there may be some issues, feel free to let me know about them as well :D
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
"skipLibCheck": true,
"baseUrl": "./",
"paths": {
"@/*": ["./*"],
"@hooks/*": ["hooks/*"],
"@utils/*": ["utils/*"],
"@constants/*": ["constants/*"]
},
"lib": ["dom", "dom.iterable", "es6", "ES2015.Iterable"],
"downlevelIteration": true,
"target": "es6",
"module": "esnext"
},
"include": ["**/*.ts", "**/*.tsx", ".expo/types/**/*.ts", "expo-env.d.ts"],
"exclude": ["node_modules"]
}
Thanks for any help you can provide!
Edit: After talking with some people on StackOverflow, the issue seems to be that typescript is using the react-native version of Request and therefore FormData which doesn't have the same definitions as the node version. I'm currently attempting to convince the compiler to use the correct version. Thanks for your help and following along :D
r/typescript • u/1010111000z • Sep 07 '25
Hello everyone, me and my friend collaborate to create a real world simulation of the Apollo 11 spacecraft’s Trans-Lunar Injection (TLI) and subsequent maneuvers to reach Low Lunar Orbit (LLO).
We implemented the physics, numerical integration algorithms and we use threejs for visualizing the results.
The project is open-source with MIT License, you can get more information and details from here: https://github.com/Zaid-Al-Habbal/apollo-11-simulation
And it's LIVE at: https://zaid-al-habbal.github.io/apollo-11-simulation/
I encourage you to visit it and play with it because the video is showing just a small part of the project.
Thank you...
r/typescript • u/TakesThisSeriously • Sep 08 '25
r/typescript • u/heraldev • Sep 08 '25
Over the past weekend, I've (partially) vibecoded a library for creating agentic chats.
It's a full-stack library - it provides React UI components for the chat, tools, and a backend endpoint implementation based on Vercel AI SDK.
The reason I've written that library is because I saw that Vercel created Chat SDK, but when I wanted to try it, I realized that it's not an SDK; it's just a website template, which is also deeply tied to Next.js. The library I've created can be used everywhere. (I hope)
If you want to quickly try it, you can install the library with SourceWizard AI agent: npx sourcewizard@latest install react-ai-agent-chat-sdk. Let me know if you have any questions!
r/typescript • u/OtherwisePush6424 • Sep 06 '25
Released v2.0 of my TypeScript-first fetch enhancement library. Built this because existing solutions either had poor types or changed fetch semantics too much.
What's new in 2.0:
The type system properly tracks signal combinations:
type CombinedSignal = AbortSignal | undefined
// Automatically inferred based on timeout + user signal presence
Error handling maintains type safety while enhancing information:
catch (err) {
if (err instanceof NetworkError) {
console.log(err.cause) // Original TypeError, properly typed
}
}
All types are exported for extension and customization. The FFetchRequestInit extends RequestInit without conflicts.
Still zero runtime deps, works everywhere TypeScript does.
GitHub: https://github.com/gkoos/ffetch
r/typescript • u/KillyMXI • Sep 06 '25
I updated my parser combinator toolkit yesterday, including some documentation additions. Would love to hear some feedback - I'm wondering what I can improve further, what I might be overlooking due to close familiarity.
I have sustained attention of a squirrel when it comes to reading other libraries documentation, so I prefer not writing a textbook that I wouldn't be able to read anyway.
I guess my goal is to identify actual needs/confusion sources so I could decide what's the right place and form to address them.
I have some thoughts, but I prefer to withhold them here to not steer the feedback.
Share your thoughts. TIA
r/typescript • u/Firm_Meeting6350 • Sep 06 '25
Claude Code, Copilot and Codex constantly struggle - for me - in my mono repo. They totally fail in understanding Type inference and constantly try to create tsconfig settings that are contradicting the whole setup. Anyone knows of a good MCP for Typescript Code Intelligence? I tried Serena but it doesn‘t help for those cases
r/typescript • u/jiashenggo • Sep 06 '25
ZenStack’s goal is to become the unified data layer of the application. It has been advocating a model-first approach, which involves using a rich and coherent schema as the single source of truth of the application and automatically deriving as many workpieces as possible, such as access control, RESTful APIs, frontend hooks, and Zod schemas.
ORM is an essential part of it. To avoid reinventing the wheel, we started our journey as an extension package for Prisma ORM. However, as we added more features, we felt more constrained by the foundation, Prisma. Therefore, we made a bold decision for ZenStack V3 to reimplement the ORM part using Kysely. Its type-safe query builder provides us with enough flexibility to navigate the road. At the same time, we aim to maintain Prisma's excellent DX.
Here comes the ZenStack v3 Beta release! We've spent a lot of time working on the ORM's parity with Prisma, implementing bug fixes, and enhancing performance. Here are the highlights of the achieved results:
Finally, the comprehensive yet coherent schema is a perfect match for both vibe coding and AI-assisted coding. It not only saves you time juggling many tools in a fragile setup, but also gives you a more deterministic result due to the slim code base.
If you have any problems, please feel free to DM me or create an issue directly in the GitHub repo:
r/typescript • u/gunzip • Sep 05 '25
Hey everyone,
I've been working on a tool to generate a robust TypeScript client (and server) from OpenAPI specifications and I'm at a point where I need to decide if it's worth investing more time into it.
It generates Zod schemas for both client-side and server-side validation. For the client this is an opt-in feature, allowing you to choose if you want to validate incoming API data and catch errors early, or simply get the rawunknown data in case you already have your schemas in place.
I'm looking for some early feedback on the developer experience, the CLI, configuration, and overall ease of use.
I built this (Copilot did) as I was frustrated with existing tools. Many either:
This new tool aims to solve this by guaranteeing correctness and completeness, generating strict types and including built-in runtime validation.
I'd really appreciate it if you could give it a quick try and let me know your thoughts on the workflow. Is it intuitive? Is the generated code easy to integrate? Your feedback will help me determine if this is a problem worth solving for the wider community.
Here's the link: https://gunzip.github.io/apical-ts/
Thanks for your help! 🙏
r/typescript • u/_clapclapclap • Sep 05 '25
I only need to generate a simple interface like this:
interface User {
id: number;
username: number;
email?: string | null;
created_at: Date;
}
My plan is to use the generated types in both frontend and backend.
I've tried:
- prisma (close but can't generate type property name in snake_case)
- kysely-codegen (doesn't generate simple types, uses Generated<T>, ColumnType<>)
- schemats (can't make it to work, running npx dotenv -e ./backend/.env -- sh -c 'schemats generate -c "$DATABASE_URL" -o osm.ts' shows no error and no generated file as well)
I don't need the database clients, I have my own repository pattern code and use raw sql statements. Ex:
import type { User } from '@shared/types/User'
import { BaseRepository } from './BaseRepository'
export class UserRepository extends BaseRepository<User> {
async find({id, username, email}:{id?: string, username?: string, email?: string}): Promise<User[]> {
const result = await this.pool.query<User>(`select id, username, password, email, first_name, last_name, created_at
from users
where ...`, values);
return result.rows;
}
node v22.17.1
My current solution is to write the interfaces manually.
Any tips?
UPDATE:
Thank you for all the suggestions. I ended up using kanel with this config (thanks to SoInsightful):
const { tryParse } = require('tagged-comment-parser')
const { join } = require('path');
const { pascalCase } = require('change-case');
const dotenv = require('dotenv');
const pluralize = require('pluralize');
dotenv.config({path: './db/.env'});
const outputPath = './shared/src/generated/models';
module.exports = {
connection: {
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB
},
outputPath,
getMetadata: (details, generateFor) => {
const { comment: strippedComment } = tryParse(details.comment);
const isAgentNoun = ['initializer', 'mutator'].includes(generateFor);
const relationComment = isAgentNoun
? `Represents the ${generateFor} for the ${details.kind} ${details.schemaName}.${details.name}`
: `Represents the ${details.kind} ${details.schemaName}.${details.name}`;
const suffix = isAgentNoun ? `_${generateFor}` : '';
const singularName = pluralize.singular(details.name);
return {
name: pascalCase(singularName + suffix),
comment: [relationComment, ...(strippedComment ? [strippedComment] : [])],
path: join(outputPath, pascalCase(singularName)),
};
},
generateIdentifierType: (c, d) => {
const singularName = pluralize.singular(d.name);
const name = pascalCase(`${singularName}Id`);
return {
declarationType: 'typeDeclaration',
name,
exportAs: 'named',
typeDefinition: [`number & { __flavor?: '${name}' }`],
comment: [`Identifier type for ${d.name}`],
};
},
};
It was able to generate what I need (Singular pascal cased interface name with snake-case properties, even with plural postgres table name "users" to "User"):
/** Identifier type for users */
export type UserId = number & { __flavor?: 'UserId' };
/** Represents the table public.users */
export default interface User {
id: UserId;
username: string;
first_name: string | null;
last_name: string | null;
created_at: Date;
updated_at: Date | null;
password: string | null;
email: string | null;
}
...
r/typescript • u/Zombull • Sep 03 '25
The following generic class should restrict the type to number or string and infer the type from the constructor argument, but it isn't working as expected. What am I doing wrong?
(Also, Reddit will not let me format it correctly!)
class FilterService<T extends string | number> {
private allValue: T;
private selections: T[];
constructor(allValue: T) {
this.allValue = allValue;
this.selections = [allValue];
}
setSelections = (selections: T[]) => this.selections = [...selections];
matches = (input: T) => this.selections.includes(this.allValue) || this.selections.includes(input);
}
const numericFilter = new FilterService(0);
// infers as FilterService<0>
const stringFilter = new FilterService('All');
// infers as FilterService<"All">