r/typescript • u/sinclair_zx81 • Sep 17 '25
Introducing TypeBox 1.0: A Runtime Type System for JavaScript
r/typescript • u/sinclair_zx81 • Sep 17 '25
r/typescript • u/patrick99e99 • Sep 18 '25
After my last fantastic post on here: https://www.reddit.com/r/typescript/comments/1mk9rzp/how_is_it_possible_that_people_actually_think/
There were many people who wanted definitive examples of why I think what I think... Well, here I am today, mad as ever, just wanting to get my work done, and I can't because TypeScript is so damn stupid and annoying. It's like TypeScript is literally anti-productivity technology. Things that should take 10 seconds to implement take ages, and the worst part is, being FORCED to write code you hate.
Example du jour:
const sroQueues = [
this.queues.sro_watermark_intermediates_complete,
this.queues.sro_watermark_complete,
this.queues.sphe_connect_titles,
].filter(queue => !!queue);
if (!sroQueues.length) {
throw new Error('sro queues do not exist!');
}
const sroResources = sroQueues.map(queue => queue.queueArn);
if (!sroResources.length) {
throw new Error('resources for SRO policy do not exist!');
}
const sroPolicy = new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
principals: [sroUser],
actions: ['sqs:SendMessage'],
resources: sroResources,
});
sroQueues.forEach((sroQueue) => {
sroQueue.addToResourcePolicy(sroPolicy);
});
Despite me, KNOWING 100% without a doubt that `sroQueues` will have queues, and WILL have `queueArn` properties set, I still went through the annoyance of once again, writing unnecessary obnoxious code, filtering out the (impossible) possibility of null/undefined items... And despite me making the unnecessary effort of writing obnoxious guard clauses to throw errors which will NEVER happen.. and I get:
```
TSError: ⨯ Unable to compile TypeScript:
lib/queue-stack.ts:145:49 - error TS2532: Object is possibly 'undefined'.
145 const sroResources = sroQueues.map(queue => queue.queueArn).filter(arn => !!arn);
~~~~~
lib/queue-stack.ts:158:7 - error TS2532: Object is possibly 'undefined'.
158 sroQueue.addToResourcePolicy(sroPolicy);
~~~~~~~~
```
So then I roll my eyes, and go to the extra obnoxious effort of putting `?` before property accessing:
`queue?.queueArn` and `sroQueue?.addToResourcePolicy`
and then I get:
```
lib/queue-stack.ts:154:7 - error TS2322: Type '(string | undefined)[]' is not assignable to type 'string[]'.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
154 resources: sroResources,
~~~~~~~~~
```
So despite FILTERING out null values, THROWING errors if there are no values, TypeScript is STILL SO INCREDIBLY STUPID AND THINKS THAT OMG THIS JUST MIGHT BE UNDEFINED, EVEN THOUGH THERE IS NO WAY IN THE WORLD THAT IS POSSIBLE...
Must be a skill issue...
But, I have a sneaking suspicion it's actually a stupid fake language issue.
r/typescript • u/eazieLife • Sep 17 '25
I want to get a list of properties in a record that are numeric enums but for all my efforts, it seems to remove numeric properties as well. I can't seem to find a reliable way of checking if a type is a numeric enum or a number.
To add a little more context, the end goal is to have something like this
enum Status {
Ok
Error
}
type SomeRecord = {
a: Status
b: number
}
type Y = EnumOnly<SomeRecord> // a
type X = NumberOnly<SomeRecord> // b
r/typescript • u/Upbeat_Buy2461 • Sep 17 '25
I'm a new TypeScript learner, and while experimented with switch, I got these weird type complaints from TypeScript.
Heres the code:
type DayOfWeek = "monday" | "friday" | "saturday" | "sunday";
let dayOfWeek: DayOfWeek = "friday";
switch (dayOfWeek) {
case "monday":
console.log("Start of work week");
break;
case "friday":
console.log("TGIF!");
break;
case "saturday":
case "sunday":
console.log("Weekend");
break;
default:
console.log("Regular Day!")
}Screenshot of the error:

Says the same thing for the other errors of course.
The errors occur when dayOfWeek is typed as DayOfWeek type. If it is typed as string, then it's fine.
Am I missing something, or is this a typescript bug?
EDIT: Solved - misunderstood how TypeScript analyzes and infers in a switch scope
r/typescript • u/ryhaltswhiskey • Sep 16 '25
I'm running into this at work. I was getting sigabrt errors during type check. This tells me that something is going wrong with our typescript. Typically a type check will take less than 1.5 seconds and complete successfully. There were some changes to imported packages and suddenly it's taking a long time and using up all the available memory and then failing.
What I don't know is how to diagnose this. I spent several hours yesterday letting an AI loose on the problem and got nowhere.
Edit: monorepo with yarn workspaces, but there are many company packages that are imported
r/typescript • u/oatsandsugar • Sep 16 '25
I wrote a guide with the ClickHouse team that shows you how you can add ClickHouse to your frontend application (in the example app, a React frontend).
Replicate data from Postgres to ClickHouse with ClickPipes. Then, point MooseStack at ClickHouse → it introspects the database to pull schemas into TypeScript models, letting you define typed APIs (runtime-validated). APIs are OpenAPI compatible, and documented, so we generate a typed React client (Kubb/Orval). Changes hot-reload in local dev. Pull remote data into your local dev environment with seed command.
Links
Guide: https://clickhouse.com/blog/clickhouse-powered-apis-in-react-app-moosestack
Repo: https://github.com/514-labs/area-code/tree/main/ufa-lite
Demo: https://area-code-lite-web-frontend-foobar.preview.boreal.cloud
Feedback wanted
Affiliation: I work at Fiveonefour (maintaining open source MooseStack). Non-tracking links. Educational write-up + code only.
r/typescript • u/Kethqwerty • Sep 15 '25
Sometimes it feels like 20–30% of my files are just type gymnastics, declaring, merging, extracting, all just to make the compiler happy and silence warnings.
God forbids I try to inspect a react type to figure out how to actually work with it, I’m dropped into puzzles like this:
type ComponentProps<T extends keyof React.JSX.IntrinsicElements | React.JSXElementConstructor<any>> = T extends React.JSXElementConstructor<infer Props> ? Props : T extends keyof React.JSX.IntrinsicElements ? React.JSX.IntrinsicElements[T] : {}I have to focus 100% to be able to understand what this type exactly expects. Nearly all my coding battles are against types not business logic.
r/typescript • u/ahjarrett • Sep 15 '25
Context: I'm working on building adapters for various TypeScript schema libraries, and I'm trying to get a sense for which library to support next.
Currently I've added support for (in alphabetical order):
Which one should I add next?
Note: I'm working on Effect now, but I've run into a few snags that I'm working out with the library author. Not sure if it will work yet 🤞
Note: Standard schema doesn't help here, please don't suggest that –– I need to be able to traverse the schema's AST.
r/typescript • u/kidusdev • Sep 15 '25
I’m trying to build a simple template engine in TypeScript inspired by Laravel’s Blade. I want it to support:
Variable output (e.g., {{ name }})
Conditionals (@if, @elseif, @else)
Loops (@for, @foreach)
Custom directives like @section, @include, etc.
I’m struggling with:
Example usage I want:
@foreach(users as user)
<p>{{ user.name }}</p> @endforeach
Expected output:
<p>Alice</p> <p>Bob</p>
I’d love guidance on:
Best practices for parsing and compiling templates in TypeScript
Whether to handle things at compile-time or render-time
Libraries or techniques for building Blade-like features
Any examples or pointers would be really helpful!
r/typescript • u/Svosha • Sep 14 '25
```ts
export async function copyToClipboard(text: string) {
const { writeText } = await import('@tauri-apps/plugin-clipboard-manager')
await writeText(text)
}
```
In the code above, will the import be done every time the function is called, or only the first time? I asked two AIs, and one said it will only be executed the first time, and the other said that whenever the function is called, it will do the import.
r/typescript • u/Own-Guava11 • Sep 14 '25
Hi community,
This is a project I've been working on for my own use and decided to share: an EVTX (Windows Event Log) parser implemented entirely in TypeScript.
It addresses a rather niche use case in Windows forensics, and I hope it will be useful to those few who face the same problem :D
Usually, you'd reach for C++/Rust/Python libraries, but I wanted something that would work seamlessly in a Node backend without the overhead and extra complexity.
Plus, proper human-readable message resolution is usually not included in existing solutions.
Highlights
.evtx files (no native deps in core module)messages module that resolves Event IDs to human-readable strings via bundled catalogs (uses better-sqlite3)Basic usage:
import { evtx } from '@ts-evtx/core';
await evtx('./Application.evtx').withMessages().forEach(e => {
console.log(e.timestamp, "|", e.eventId, "|", e.message);
});Output:
2025-06-08T07:12:16.203Z | 15 | Updated Windows Defender status successfully to SECURITY_PRODUCT_STATE_ON.
2025-06-08T07:12:56.663Z | 16384 | Successfully scheduled Software Protection service for re-start at 2025-06-09T07:10:56Z. Reason: RulesEngine.
2025-06-08T07:13:05.979Z | 16394 | Offline downlevel migration succeeded.
...Repo / Packages
The package gets the job done as-is, but I'm planning some improvements and cleanups. If you have ideas or feedback, feel free to reach out! :)
Thanks!
r/typescript • u/ridesano • Sep 14 '25
I am creating an API test to verify search. I am currently facing a problem trying to pass a subset of an object.
I am trying to create the items of this keyword object:
export type Keywords ={
type: string;
items: {
keyword: string;
type: string[];
keywordType: string;
}[];
id: string;
}This in itself, is inside an object (search). I created a method to define the properties in the items object.
withKeywords(items: {keyword: string; type: string[]; keywordType: string;}[])
{
this.criteria.keywords.items = items
return this;
}When I am calling this is how I do it
const search = search
.withKeywords(['attach', ['email'], 'KEYWORDS'])This is where I get the error. cannot read properties of undefined (reading 'items')
When hovering on the string, I am passing it states the type string is not assignable to type. I am sorry if this is not as clear I am not the best at typescript, but I am open to providing more info.
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