r/typescript • u/yashmakan • Jan 27 '26
AxiomCore/rod: The Write-Once, Validate-Anywhere Schema Library.
r/typescript • u/yashmakan • Jan 27 '26
r/typescript • u/spla58 • Jan 27 '26
The type MapNamesToClasses will map an array of strings of class names to their corresponding class object in an array. But I want it to map it as an key/value pair instead.
I want Result to be {"a": A, "b": B} instead of [A, B]
type Result = MapNamesToClasses<["a", "b"]>Here's an example of what I'm going for:
r/typescript • u/Just_Vugg_PolyMCP • Jan 27 '26
Hey everyone!
I built PolyMCP, a framework that lets you turn any Python or TypeScript function into an MCP (Model Context Protocol) tool that AI agents can call directly — no rewriting, no complex integrations.
It works for everything from simple utility functions to full business workflows.
Python Example:
from polymcp.polymcp_toolkit import expose_tools_http
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
app = expose_tools_http([add], title="Math Tools")
# Run with: uvicorn server_mcp:app --reloadTypeScript Example:
import { z } from 'zod';
import { tool, exposeToolsHttp } from 'polymcp';
const uppercaseTool = tool({
name: 'uppercase',
description: 'Convert text to uppercase',
inputSchema: z.object({ text: z.string() }),
function: async ({ text }) => text.toUpperCase(),
});
const app = exposeToolsHttp([uppercaseTool], { title: "Text Tools" });
app.listen(3000);Business Workflow Example (Python):
import pandas as pd
from polymcp.polymcp_toolkit import expose_tools_http
def calculate_commissions(sales_data: list[dict]):
df = pd.DataFrame(sales_data)
df["commission"] = df["sales_amount"] * 0.05
return df.to_dict(orient="records")
app = expose_tools_http([calculate_commissions], title="Business Tools")Why it matters:
•Reuse existing code immediately: legacy scripts, internal APIs, libraries.
•Automate complex workflows: AI can orchestrate multiple tools reliably.
•Cross-language: Python & TypeScript tools on the same MCP server.
•Plug-and-play: no custom wrappers or middleware needed.
•Input/output validation & error handling included out of the box.
Any function you have can now become AI-ready in minutes.
r/typescript • u/Xenni • Jan 24 '26
Hey all, I'm one of the folks behind Documenso (open-source doc signing). We just open-sourced LibPDF, a TypeScript PDF library we've been working on for a while.
Backstory: we spent years duct-taping pdf-lib and a custom Rust signing library together. It mostly worked, but every few weeks some customer would upload a PDF that broke something. Which led to us writing a bunch of workarounds that would make us deviate further and further from the library that we were using.
So we finally wrote the library we actually needed:
API is heavily inspired by pdf-lib (if you've used it, this will feel familiar). Font subsystem is a TS port of Apache PDFBox's fontbox.
The library is still in beta. We're using it in production but wouldn't be shocked if you have some weird PDFs that find bugs we haven't hit yet.
Docs: https://libpdf.dev
Blog: https://documenso.com/blog/introducing-libpdf-the-pdf-library-typescript-deserves
r/typescript • u/HumanCertificate • Jan 24 '26
I need to deconstruct an object that is received from await supabase.from("profiles").select("user_id").eq("username", searchedUsername);. However, I'm having trouble figuring out how to know the return type of these .select, .eq methods are.
My first intuition was to hover over the .eq("username", serachedUsername); to learn the return type, but I got this.
(method) PostgrestFilterBuilder<any, any, any, { user_id: any; }[], "profiles", unknown, "GET">.eq<"username">(column: "username", value: any): PostgrestFilterBuilder<any, any, any, {
user_id: any;
}[], "profiles", unknown, "GET">
Match only rows where column is equal to value.
To check if the value of column is NULL, you should use .is() instead. To me this is just incomprehensible, and I don't know where to begin. What does this mean? What should I check to learn about these? This look nothing like the return type that is
const object: PostgrestSingleResponse<{
user_id: any;
}[]>Also, currently the way I find out the return type of a function is just writing const object = function(); and hovering over the object to see what the type is. Is there an alternative? I feel like you should be able to know the return type by just hovering over a function.
r/typescript • u/aliassuck • Jan 24 '26
I want to do this:
document.querySelector("div").ontransitionend = function (e: TransitionEvent) {
const div = this as any as HTMLDivElement;
if (e.target === div) {
// do thing
}
}But typescript complains that "this" is an any and won't allow the above line attempt either.
r/typescript • u/InternalServerError7 • Jan 21 '26
ts2rs is cli and programmatic api for converting typescript types to rust types. Nested types are even traversed across packages and resolved. Meaning if your types includes other types in different packages it will traverse those to resolve the shape. With this tool you can write your definitions in typescript and generate the equivalent rust types which support bi-directional json serialization.
e.g.
example.ts
export type Shape =
| { type: "circle"; radius: number }
| { type: "rectangle"; width: number; height: number }
| { type: "triangle"; base: number; height: number };
use ;
This came about because I was working on an api that was primarily driven on the typescript side and I already had typescript types. Rather than tediously rewrite the same api in rust with the possibility of bugs, I decided to automate it. I tinkered with the idea for a bit then when I got a few days off, I made a repo and totally wasted my "days off" on this project as I have been working full-time the past few days on it.
Now my project uses the programmatic api in my build.ts script to generate the rust types I need, which does make me very happy.
r/typescript • u/5Ping • Jan 21 '26
Right now im just using the as keyword to make it ignore errors. But what would be the proper way of doing this? I have a type: SomeType and it has a lot of keys. I need to iterate through each key and do some logic, so I am using Object.keys, but since it outputs string[ ], auto complete doesnt work and I have to use as (keyof SomeType)[]
Is as keyword actually acceptable here? Because it is essentially implied that you are definitely getting the keys of SomeType by passing it to Object.keys() ?
r/typescript • u/simwai • Jan 21 '26
I’ve been annoyed for years by how messy console logging can get once you mix:
console.log everywhereSo I built Colorino, a small, MIT‑licensed logger that tries to solve that in a “zero‑config but still flexible” way:
console (log/info/warn/error/debug/trace).dracula, catppuccin-*, github-light.neverthrow, MIT) for Result handling; no deep dependency trees.Example with the Dracula palette:
import { createColorino } from 'colorino'
const logger = createColorino(
{ error: '#ff007b' },
{ theme: 'dracula' },
)
logger.error('Critical failure!')
logger.info('All good.')
Repo + README with more examples (Node, browser via unpkg, environment variables, extending with context methods, etc.):
I’d love feedback from people who:
If you have strong opinions about logging DX or color handling (ANSI‑16 vs ANSI-256 vs Truecolor), I’m very interested in your criticism too.
r/typescript • u/spla58 • Jan 21 '26
I have a class Example that takes a list of class names in it's constructor and calls a method getClasses to set the property this.classes. I want TypeScript to be aware of the class for each element of the property this.classes . If I call getClasses directly it works but it does not work when setting the property in the constructor. This a follow up to another question I asked: https://www.reddit.com/r/typescript/comments/1qdu678/how_can_i_create_a_method_that_returns_a_list_of/
Here is my example:
r/typescript • u/hewmax • Jan 21 '26
Setup: TypeScript backend, Node.js. Need to call LLM API, get JSON response, use it for business logic. No chat UI.
Problem: Direct API calls (OpenAI, Anthropic) return JSON wrapped in text — markdown blocks, preambles like "Here's your response:". Regex parsing is unreliable. Sometimes model returns clarifying questions instead of answer.
Tried:
Looking for:
Constraints: Prefer lightweight solution. LangChain seems heavy for this use case.
What's the standard approach here?
r/typescript • u/Ok_Biscotti_2539 • Jan 19 '26
I'm trying to use a library written in TS in a non-Node JS runtime environment. Specifically in an Adobe UXP plug-in. The library is to write Word files: dolanmiu/docx: Easily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.
I found what appears to be a JS build of it and tried importing it into my plug-in's JavaScript, but it fails with "Error: Cannot find module 'stream'". I don't know where it's looking for this.
Anyway, I'm pretty new to TS/JS and was wondering how or if I can compile this thing into JS that I can call in my plug-in without Node.
r/typescript • u/ThreadStarver • Jan 17 '26
So I was dealing with a basic function in TS that looked something like this
function do_something() {
if (someCase) {
return { success: false, skipped: true }
}
return { success: true, skipped: false };
}
Now on checking I observed that it infers the return type of function as { success: boolean, skipped: boolean }; Now I wanted it to be strict that it should only be one of the 2 cases that I return but it takes any possibility where both are boolean, I can infer the return type of the function to be strictky among those 2, but after a bit research realised that it's an anti pattern and we should let TS infer type automatically as much as possible. But then why does TS show liniency here? Also there is no option in tsconfig to make it that strict. So what's the best pattern to use. Any help is really appereciated
r/typescript • u/TheWebDever • Jan 17 '26
Sorry if this is a dumb question, I love TypeScript most of the time, but I can't stand the "Type Gymnastics" I sometimes have to do to resolve complex types. Mostly I think this stems from ternary statements being the only kind of boolean logic allowed for resolving types. This results in deeply nested and overly complex types that are often hard to understand. Does anyone think it would be easier to resolve complex types if they could be defined in a normal 'function' styles format.
If you wanted to resolve the params in a string URL you'd currently have to do:
type RouteParams<T extends string> = T extends ${string}:${infer P}/${infer R} ? P | RouteParams<R> : T extends ${string}:${infer P} ? P : never;
Wouldn't it be nice if we could do something like:
type RouteParams<T extends string> { if (T extends ${string}:${infer P}/${infer R}) { resolve P | RouteParams<R>; } else if (T extends ${string}:${infer P}) { resolve P; } // Can do else or never inferred if else is left off // else { // resolve never; // } }
type Params = ResolveParams<'/user/:email/:id'> // => 'email' | 'id';The new name for this feature could be *type-blocks*
**Edit**
So people are saying they like the idea of avoiding nested ternaries but don't think it should be an if/else style statement. I think something besides if/else is fine as long as we don't have to do complicated 'nesting'. Here's another suggestion: the new **eval/resolve** statement (more similar to `switch`/`case`):
type RouteParams<T extends string> {
// allow for another type-declarations up here
// i.e type K = T[];
eval (T extends `${string}:${infer P}/${infer R}`):
resolve P | RouteParams<R>;
eval (T extends `${string}:${infer P}`):
resolve P;
eval:
resolve never;
}r/typescript • u/ZtaDev • Jan 17 '26
¡Hola a todos! Quería compartir un proyecto llamado Pulse-JS.
Aunque hay muchos gestores de estado por ahí (Zustand, Signals, TanStack), Pulse-JS tiene un enfoque único al tratar las Business Conditions como ciudadanos de primera clase. En lugar de solo gestionar datos, se enfoca en gestionar la lógica que gobierna tu app. Creado con TypeScript.
La innovación principal es el Semantic Guard. A diferencia de un simple booleano o una señal computada, un Guard es una primitiva reactiva que rastrea:
ok, fail, o pendingguard.all(), guard.any(), y guard.not(). Construye reglas complejas (por ejemplo, ¿Puede el usuario pagar?) que son legibles y modulares.<pulse-inspector>) para visualizar tu gráfico lógico e inspeccionar las razones de fallo en tiempo real, sin importar el framework.evaluate() y hydrate() para prevenir parpadeos de hidratación.Pulse-JS maneja la lógica asíncrona de forma nativa. Puedes definir un Guard que obtenga datos y encapsule toda la condición comercial.
import { guard } from '@pulse-js/core';
import { usePulse } from '@pulse-js/react';
// 1. Define una regla de negocio semántica con lógica asíncrona
const isAdmin = guard('admin-check', async () => {
const response = await fetch('/api/user');
const user = await response.json();
if (!user) throw 'Authentication required';
if (user.role !== 'admin') return false; // Falla con la razón predeterminada
return true; // ¡Éxito!
});
// 2. Consúmelo en tu interfaz de usuario
function AdminPanel() {
const { status, reason } = usePulse(isAdmin);
if (status === 'pending') return <Spinner />;
if (status === 'fail') return <ErrorMessage msg={reason} />;
return <Dashboard />;
}Me encantaría saber qué opinan sobre este enfoque de la reactividad centrado en la lógica.
r/typescript • u/TNDQ • Jan 16 '26
So I noticed you can kind of copy an array by spreading it into an object (not the recommended way obviously)
const arrayCopy = { ...[1, 2, 3, 4] };TypeScript thinks that the type of arrayCopy includes ALL the properties and method on the array
const arrayCopy: {
[n: number]: number;
length: number;
toString(): string;
toLocaleString(): string;
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions & Intl.DateTimeFormatOptions): string;
pop(): number | undefined;
push(...items: number[]): number;
concat(...items: ConcatArray<number>[]): number[];
concat(...items: (number | ConcatArray<number>)[]): number[];
join(separator?: string): string;
reverse(): number[];
shift(): number | undefined;
slice(start?: number, end?: number): number[];
sort(compareFn?: ((a: number, b: number) => number) | undefined): number[];
... 20 more ...;
[Symbol.unscopables]: {
...;
};
}But the vast majority of these properties don't actually get copied over since they are non-enumerable. The actual object yielded looks like this:
{ '0': 1, '1': 2, '2': 3, '3': 4 }so this code passes the type checker but fails to run
arrayCopy.forEach((x) => console.log(x));
// Uncaught TypeError: arrayCopy.forEach is not a functionBug in TS? Feels like someone would have noticed this before
r/typescript • u/_BelowAverageHuman_ • Jan 15 '26
I have a technical 45 minute interview coming up and have less than 3 days to prep/brush up on my TS skills, any advice on how to prep for this round - will I have to write logic or debug existing code?
Here is what that they mentioned in the email "The interview format will be a Typescript problem in CodeSandbox, with you implementing some of the underlying logic in an existing feature on our software."
r/typescript • u/spla58 • Jan 15 '26
I need to create a method that takes as an argument a list of class names. The method must then return an array of the instances of the classes to the user so they can use them in a test. The problem is if I get a list back I have no typing information to determine which item in the list is which class. How can I handle this?
Here's an example:
r/typescript • u/hongminhee • Jan 15 '26
r/typescript • u/laphilosophia • Jan 14 '26
r/typescript • u/riktar89 • Jan 15 '26
Now Rikta can talk with any LLM model!
This package brings Model Context Protocol (MCP) support to the Rikta framework, allowing you to build standardized interfaces between AI models and your data sources.
Key capabilities:
- Seamless integration with AI agents and LLMs.
- Standardized tool-calling and resource access.
- Simplified data bridging for the Rikta ecosystem.
Get started: https://rikta.dev/blog/introducing-rikta-mcp
r/typescript • u/drinikol • Jan 14 '26
const
[flowersData, setFlowersData] = useState<Flower[]>();
export
interface
Flower {
id:
string
,
name:
string
,
color: Color |
null
,
quantity:
number
|
null
,
}
const onChangeValue = (data:Flower, index:number)=>{
var tempList: Flower[] = [...flowersData];
const
newData = (data as Flower);
const
newList = tempList.map((
item
,
_index
) => {
if (_index === index) {
return newData;
}
return item;
});
//tried this but the same result
// tempList[index] = newData;
setFlowersData(newList);
}Good day! I am learning Next.Js Typescript. I have an issue updating a specific element in my array. For example if I update a certain index, all elements with the same id, are being updated.
I only want to update certain index / element's color and quantity but I can't manage to make it work.
r/typescript • u/riktar89 • Jan 13 '26
Hi all!
I wanted to share a project I’ve been working on: Rikta.
The Problem: If you’ve built backends in the Node.js ecosystem, you’ve probably felt the "gap." Express is great but often leads to unmaintainable spaghetti in large projects. NestJS solves this with structure, but it introduces a constant management of imports: [], exports: [], and providers: [] arrays just to get basic Dependency Injection (DI) working.
The Solution: I built Rikta to provide a "middle ground." It offers the power of decorators and a robust DI system, but with Zero-Config Autowiring. You decorate a class, and it just works.
Key Features:
Open Source
Rikta is MIT Licensed. I believe the backend ecosystem needs more tools that prioritize developer happiness and "sane defaults" over verbose configuration.
I’m currently in the early stages and looking for:
Links:
I’ll be around to answer any questions about the DI implementation, performance, or the roadmap!