You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Zod Schema推断出以A开头的TypeScript字符串类型?

解决Zod推断前缀字符串类型不匹配的问题

Zod 默认的 .startsWith() 方法只会做运行时校验,但不会细化 TypeScript 推断类型,你可以通过以下两种方式让推断类型和定义的 A${string} 保持一致:

方法一:用 z.custom() 自定义校验与类型

直接通过 z.custom() 同时指定类型和运行时校验逻辑,一步实现需求:

import { z } from 'zod';

type StringStartsWithA = `A${string}`;

const StringStartsWithASchema = z.custom<StringStartsWithA>(
  (val): val is StringStartsWithA => 
    typeof val === 'string' && val.startsWith('A')
);

// 此时推断出的类型就是 StringStartsWithA
type InferredType = z.infer<typeof StringStartsWithASchema>; // 类型为 `A${string}`

方法二:扩展 Zod 的 StringSchema 方法

如果想保留 Zod 链式调用的风格,可以扩展 Zod 的字符串方法,让 .startsWith() 自动返回细化后的类型:

import { z } from 'zod';

// 扩展 Zod 的类型声明
declare module 'zod' {
  interface StringSchema<T extends z.ZodStringDef> {
    startsWith<const P extends string>(prefix: P): z.ZodType<`${P}${string}`, z.ZodStringDef & { prefix: P }, string>;
  }
}

// 实现扩展的 startsWith 方法
z.String.prototype.startsWith = function(prefix) {
  return this.refine(
    (val) => val.startsWith(prefix),
    { message: `字符串必须以 "${prefix}" 开头` }
  ) as typeof this & z.ZodType<`${typeof prefix}${string}`>;
};

// 现在使用方式和原来一样,但推断类型正确了
const StringStartsWithASchema = z.string().startsWith("A");
type InferredType = z.infer<typeof StringStartsWithASchema>; // 类型为 `A${string}`

第一种方式适合单个场景快速落地,第二种方式更适合项目中多次用到前缀校验的情况,能保持代码风格统一。

内容的提问来源于stack exchange,提问作者Gergely Fehérvári

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 17:20:31