Skip to content

bug(zod): zx.toType doesn't handle z.templateLiteral with z.enum, z.nullable, z.optional #521

@gnlow

Description

@gnlow

Minimal Reproduction

import { z } from "https://esm.sh/zod@4.1.9"
import { zx } from "https://esm.sh/@traversable/zod@0.0.48"

console.log(
    zx.toType(z.templateLiteral([
        "Hello, ",
        z.union([z.string(), z.number()]),
    ]))
)

console.log(
    zx.toType(z.templateLiteral([
        z.enum(["a", "b"]),
        z.literal(["c", "d"]),
    ]))
)

console.log(
    zx.toType(z.templateLiteral([
        z.number().nullable(),
        "px",
    ]))
)

console.log(
    zx.toType(z.templateLiteral([
        z.number().optional(),
        "px",
    ]))
)

Expected

`Hello, ${string}` | `Hello, ${number}`
"ac" | "ad" | "bc" | "bd"
`${number}px` | "nullpx"
"px" | `${number}px`

Actual

"Hello, [object Object]"
"[object Object]c" | "[object Object]d"
"[object Object]px"
"[object Object]px"

note

  • I'm not sure whether the last one should be "px" | `${number}px` or `${number}px` | "undefinedpx".
    • The z.templateLiteral has z.ZodTemplateLiteral<"px" | `${number}px` type.
    • type A = `${number | undefined}` seems to be handled as type A = `${number}` | "undefined" in TypeScript.
    • Maybe it's intended behavior of Zod (Add z.literal.template() colinhacks/zod#1786).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions