以字母开头的字符串的 Zod 模式

问题描述 投票:0回答:2

我在打字稿中有这种类型,字符串必须以

A
字母开头。

type StringStartsWithA = `A${string}`

当我想创建 zod 模式时,这就是我使用的:

const StringStartsWithASchema = z.string().startsWith("A")

但是推断出的类型只是一个普通的字符串。

type StringStartsWithA = z.infer<typeof Schema> // string

有没有办法解决这个问题,所以推断类型也需要以

A
字母开头?那么它会匹配原始的打字稿类型吗?

typescript zod
2个回答
3
投票

来自文档

您可以使用以下命令为任何 TypeScript 类型创建 Zod 架构 z.custom().这对于为非类型创建模式很有用。 Zod 开箱即用地支持,例如模板字符串文字。

const px = z.custom<`${number}px`>((val) => /^\d+px$/.test(val));
px.parse("100px"); // pass
px.parse("100vw"); // fail

所以,针对您的情况:

const StringStartsWithA = z.custom<`A${string}`>((val: any) => /^A/.test(val));
type StringStartsWithA = z.infer<typeof StringStartsWithA> // type StringStartsWithA = `A${string}`

0
投票

您还可以执行以下操作


const px = z.string().endsWith('px').and(z.custom<`${string}px`>());
px.parse('100px'); // pass
// px.parse('100vw'); // fail

这还允许您继续使用字符串实用程序,例如 .max、.length 等...

© www.soinside.com 2019 - 2024. All rights reserved.