Recursive types(typescript and zod validation)

Feb 06, 2024

要寫程式,不要學程式

正在把 react-hook-formtiptap 做結合,用 zod作為驗證手段,發現有關 tiptap的 content type如下

type JSONContent = { type?: string attrs?: Record<string, any> content?: JSONContent[] marks?: { type: string attrs?: Record<string, any> [key: string]: any }[] text?: string [key: string]: any }

content本身呈現 recursive的相互引用,而用zod作為驗證工具則要先定義schema,參考官方文件改寫為驗證content的schema如下

const baseContent = z.object({ type: z.string(), attrs: z.record(z.any()) .optional(), marks: z.array( z.object({ type: z.string(), attrs: z.record(z.any()) .optional(), }) ).optional(), text: z.string().optional() }); type Content = z.infer<typeof baseContent> const EditorSchema : z.ZodType<Content> = baseContent.extend({ content: z.array(z.lazy(() => EditorSchema)).optional() })
  1. 不重複的欄位先定義成base
  2. 將base定義成一個type
  3. 將base extend 會 recursive的key

程式都是寫出來的,一個實際的問題,堆疊了很多用法來解決,最好的學習就是實際的寫,用批判的方式,尋找所有可行性,問題的解法永遠都不只一種,更不能止於一種。

Ekman Hsieh
Ekman Hsieh

文字工作者,寫作時間常常在人類與電腦之間拉鋸,相信閱讀,相信文字與思想所構築的美麗境界