Created
May 25, 2023 03:04
-
-
Save vnphanquang/7b7f0ad856c397a3be8e5a45fd035bcc to your computer and use it in GitHub Desktop.
Validation of i18n translation json using zod
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://zod.dev/ | |
import { z } from 'zod'; | |
import ja from './ja.json'; | |
import en from './en.json'; | |
type RecursiveStringRecord = { | |
[key: string]: string | RecursiveStringRecord; | |
} | |
type RecursiveZodStringRecord = { | |
[key: string]: z.ZodString | RecursiveZodStringRecord; | |
} | |
type ZodStringRecord<T extends RecursiveStringRecord> = { | |
[key in keyof T]: T[key] extends string | |
? z.ZodString | |
: T[key] extends RecursiveStringRecord | |
? z.ZodObject<ZodStringRecord<T[key]>> | |
: never; | |
} | |
function zodify<T extends RecursiveStringRecord>(obj: T): ZodStringRecord<T> { | |
const zodified = {} as RecursiveZodStringRecord; | |
for (const key in obj) { | |
if (typeof obj[key] === 'string') { | |
zodified[key as any] = z.string(); | |
} else { | |
zodified[key as any] = z.object(zodify(obj[key] as any)) as any; | |
} | |
} | |
return zodified as ZodStringRecord<T>; | |
} | |
const jaZod = zodify(ja); | |
const Translation = z.object(jaZod); | |
Translation.parse(ja); | |
Translation.parse(en); | |
export const translations = { en, ja } as const; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment