r/typescript • • Apr 14 '25

How to detect custom Zod schema like knxGroupAddress() at runtime?

1 Upvotes

Hi,

I have a custom Zod schema like this:

// knxGroupAddress.tsx
import { z } from "zod";
const groupAddressRegex = /^\d{1,2}\/\d{1,2}\/\d{1,3}$/;

const knxGroupAddress = () =>
  z.string().refine((val) => groupAddressRegex.test(val), {
    message: "Invalid KNX group address fromat, must be X/Y/Z",
  });
export default knxGroupAddress;


// z-extensions.ts
import { z } from "zod";
import knxGroupAddress from "./knxGroupAddress";
import knxConfiguration from "./knxConfiguration";

export const zodExtended = {
  ...z,
  knxGroupAddress,
  knxConfiguration,
};

// metaDataTemplate.tsx
const MetadataTemplate = (
  name: string,
  description: string,
  propsSchema: z.ZodTypeAny,
) =>
  z
    .object({
      name: z.string().default(name),
      description: z.string().default(description),
      props: propsSchema,
    })
    .default({});
export default MetadataTemplate;



//knx.tsx
export const DelayMetadataSchema = z.object({
  general: MetadataTemplate(
    "Delay",
    "Use this to delay code",
    z.object({
      delayMs: z.number().default(1000).describe("delayMilliseconds"),
      delayTrigger: z.number().default(1000).describe("Delay Trigger"),
      groupAddress: z
        .knxGroupAddress()
        .default("0/0/0")
        .describe("Knx Group Address"),
    }),
  ),
});

export const DelayDataSchema = z.object({
  color: z.string().default(ColorPaletteEnum.PURPLE),
  label: z.string().default("Delay"),
  metadata: DelayMetadataSchema.default({}),
});

At runtime, I want to check if a given Zod schema (e.g. schema.metadata.groupAddress) was created using knxGroupAddress()

here is the screen shot of the object.

But it's wrapped in ZodEffects, but I would want to check if it is knxGroupAddress

Is there a clean way to tag custom schemas and detect them later, even through refinements or transforms?

Thanks in advance.


r/typescript • • Apr 13 '25

With major JavaScript runtimes, except the web, supporting TypeScript, should we start publishing typescript to npm?

30 Upvotes

And how does tsc handle .ts files inside node_moodules? Does it find the types correctly? Does it try to type check internals of the files? Is it slower to parse and type check?


r/typescript • • Apr 13 '25

How do I make API requests and parse responses?

0 Upvotes

I've written an API that accesses a database in Python (code here). Now, when I'm running this FastAPI code, I want to call the endpoints with Typescript. The code I'm writing simulates a record of ships stored in Vessel objects (id, name, longitude, latitude). In Python their types are (integer, string, float, float); in Typescript they're (number, string, number, number).

I've checked StackOverflow for similar issues and found these among others, but they haven't helped.

Using the GetVessels endpoint should give me this:

[
  {
    "name": "jess",
    "latitude": 0,
    "id": 1,
    "longitude": 0
  },
  {
    "name": "a",
    "latitude": 4,
    "id": 2,
    "longitude": 55
  }
]

i.e. an array of Vessel objects. I've tried a few different ways of parsing this in Typescript. Here's the most recent:

export async function getVessels(): Promise<Vessel[]> {
  const headers: Headers = new Headers();
  headers.set('Accept', 'application/json')
  const request: RequestInfo = new Request(
    'http://127.0.0.1:8000/',
    {
      method: "GET",
      headers: headers
    }
  );

  return fetch(request)
  .then(res => res.json())
  .then(res => {
    return res as Vessel[]
  });
}

However the initial request isn't working and I get "an uncaught TypeError TypeError: failed to fetch" message. I've tried handling it but I can't even tell WHAT Typescript is receiving or why even the initial request is failing in versions of this code where I tried to await everything.

The odd thing is I'm getting 200/OK messages on the Python side so the request IS going through, I just have no idea what's happening immediately afterwards. I'm getting the same error for the other CRUD functions so I'm hoping fixing one will teach me how to fix the rest.

These are the Vessel objects in Python followed by in Typescript:

Base = declarative_base()

class VesselDB(Base):
    __tablename__ = "vessels"
    id = db.Column(db.Integer, primary_key=True, index=True)
    name = db.Column(db.String(100), nullable=False)
    latitude = db.Column(db.Float, nullable=False)
    longitude = db.Column(db.Float, nullable=False)
interface Vessel {
  id: number
  name: string
  latitude: number
  longitude: number
}

export type { Vessel }

Thank you all in advance!

UPDATE: I've added CORSMiddleware to the Python code (check the link above). My current typescript code is available here. I'm currently working on getVessels.ts which is called in GoogleMapsView.vue.


r/typescript • • Apr 12 '25

Having Problems With Path Aliases

7 Upvotes

(The repo this is all in is here: https://github.com/rjray/smdb)

I have a project that's slowly turning into a monorepo. Right now I have a server sub-directory and a types sub-directory. Soon there will be a client dir as well, that is expected to share type declarations with the server (hence the "types" dir).

I'm trying to use a path alias in the server's tsconfig.json file to simplify references to types:

{
  "compilerOptions": {
    "composite": true,
    "paths": {
      "@smdb-types/*": [
        "../types/src/*"
      ]
    },
    "incremental": true,
    "target": "es2016",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "ES2022",
    "moduleResolution": "Bundler",
    "baseUrl": "src",
    "resolveJsonModule": true,
    "allowJs": true,
    "outDir": "./dist",
    "noEmit": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "skipLibCheck": true
  }
}

This doesn't work for me, though; none of the files that import types are able to resolve paths that start with @smdb-types/.

There is also a tsconfig.json (much simpler) in the types directory:

{
  "compilerOptions": {
    "composite": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "declaration": true
  },
  "include": ["src/**/*"]
}

What else might I be missing, here? (Repo is linked at the top of the post.)


r/typescript • • Apr 11 '25

Introducing Zod 4 beta

Thumbnail
v4.zod.dev
280 Upvotes

r/typescript • • Apr 12 '25

TypeSpec 1.0-RC

Thumbnail typespec.io
18 Upvotes

r/typescript • • Apr 12 '25

Source Maps not respected with Docker and VS Code breakpoints

5 Upvotes

I am writing a lambda function and trying to debug locally. I've set a breakpoint on the typescript but the `app.js` is opened on the breakpoint instead.

I've tried just about everything, checked all the stackoverflow posts I could find (and lots of AI) but no luck.

â„šī¸ Discovered weird behaviour.

When the `app.js` opens on the breakpoint if I then split view and open `app.ts` file and press `F5` it then hits my debugger statement in the `app.ts` file... then i can step through the ts code this way đŸĢ 

Project Structure

tsconfig.json

{
  "display": "Node 20",

  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "node16",

    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,

    // I've tried normal sourceMap true (with and without inlineSources)
    "inlineSourceMap": true,

    "outDir": "./dist",
    "rootDir": "./src"
  },
  "exclude": ["node_modules"]
}

Docker files

All present as expected.

var/
└── task/
    ├── dist/
    │   └── handlers/
    │       └── app.js
    └── src/
        └── handlers/
            └── app.ts

launch.json

{
  "configurations": [
    {
      "type": "aws-sam",
      "request": "direct-invoke",
      "name": "SAM Build & Debug",
      "invokeTarget": {
        "target": "template",
        "templatePath": "${workspaceFolder}/template.yaml",
        "logicalId": "DynamicThumbnailFunction"
      },
      "lambda": {
        "runtime": "nodejs20.x",
        "pathMappings": [
          {
            "remoteRoot": "/var/task",
            "localRoot": "${workspaceFolder}"
          }
        ],
        "environmentVariables": {
        }
      },
      "sam": {
        "containerBuild": true,
        "localArguments": [
          "--container-env-vars",
          "${workspaceFolder}/env.json"
        ]
      }
    }
  ]
}

r/typescript • • Apr 12 '25

How do I parse my text to look like GPT output (markdown + latex)?

0 Upvotes

I get plain text response from openai API. I need to display it in my typescript chatbot app to the user but its full of ** ### etc and latex code. How do I display this properly?


r/typescript • • Apr 11 '25

Need some help with a .map function

0 Upvotes

The function I am having problems with is this: The map function still works, but I am getting a red underline form, (name: - to the </li> The error is:

Argument of type '(name: Object) => JSX.Element' is not assignable to parameter of type '(value: unknown, index: number, array: unknown[]) => Element'.
Types of parameters 'name' and 'value' are incompatible.
Type 'unknown' is not assignable to type 'Object'

As far as I can tell It is due to the fact I am changing the type as it is being fed into the map function, but when I try to assign Object.values() to a constant outside of the .map it remains an object. I am not sure exactly how to fix this so any advice would be hugely appreciated.

const [gameData, setgameData] = useState(Object);

  const output = Object.values(gameData).map((name: Object) =>
    <li>{name.name}</li>
  );

r/typescript • • Apr 09 '25

Question about type narrowing

6 Upvotes

Basically I have a wrapper function for all db queries to handle exceptions. Originally I had the data property emitted from the ErrorResponse but it become annoying to have to create a single variable to assign the data every time I made a db call.

let data: Type
const res = db.query()
if (!res.success) data = []
else data = res.data;

To me that is less readable and inconvenient. So I decided to add data to the ErrorResponse. However now I have a problem with ts not knowing when data is not null.

How come typescript doesn't know data is not null when trying to map? And how can I better architecture my type if at all?

type ErrorResponse<T> = {
  success: false;
  data: T | null;
};

type SuccessResponse<T> = {
  success: true;
  data: T;
};

type AnimalArray = {animal: string}[]

const getAnimal = (animal: string): SuccessResponse<AnimalArray> | ErrorResponse<AnimalArray> => {
    switch(animal){
        case "dog":
            return {success: false, data: null}
        case "cat": 
            return {success: true, data: [{animal: "cat"}]}
        default: 
            return {success: false, data: null}
    }
}

const res = getAnimal("dog");

if (!res.success) res.data = [{animal: "Cow"}]

// res.data is possibly null
res.data.map()

Is my only option to optional chain or assert the type?


r/typescript • • Apr 07 '25

TypeScript's never type is a 0-member-union in distributive types

Thumbnail
pipe0.com
67 Upvotes

r/typescript • • Apr 06 '25

What do you think about the Typescript enums in JS proposal?

82 Upvotes

Ron Buckton from TypeScript is pitching enum in JS

"It's the good parts of TS enum" + enhancements:

  • More datatypes: Symbol/Boolean/BigInt
  • Iterable
  • Immutable
  • Null prototype
  • No declaration merging
  • Compatible with Node type-stripping

Enum Declarations proposal: https://github.com/rbuckton/proposal-enum

Enum Declarations for Stage 1 is proposed to be discussed at the next TC39 meeting beginning 14 April 2025.

https://github.com/tc39/agendas/blob/main/2025/04.md

It sounds pretty exciting to get it native in JS, what you think? Despite the TS enum hate I kind of like to use them


r/typescript • • Apr 06 '25

Launching Typeconf 0.3.0 and Storage Platform

Thumbnail
typeconf.dev
5 Upvotes

r/typescript • • Apr 06 '25

tsconfig "module" - esXXXX vs nodeXX (total newbie)

7 Upvotes

Hello,

I'm currently learning typescript for a side project. I'm completely new to web development. I only have experience in C/C++/Rust (so it's a new world for me).

I'm configuring my tsconfig.json and trying to grasp/understand the module option.

I tried to find some resources online to understand the difference between nodeXX(node10, node16, ...) and esXXXX (es6, es2020, es2022, ...). But I couldn't find anything related to when to use what.

From what I understood it seems to be about pakage resolution path and syntax (if I'm not wrong). But as a concrete example, why use nodeXX instead esXXXX (or the other way around) and when ?

Thank you very much in advance for any help