Escriu per cercar…

Firebase

By combining Zod with Firestore’s `withConverter` API, you can enforce type safety at the boundary between your app and the database.

Introduction

Firestore is a powerful, flexible NoSQL database — but with great flexibility comes the risk of subtle data shape bugs, especially in TypeScript projects where runtime and compile-time types can easily diverge.

Firestore’s SDKs is powerful, but they don’t enforce your TypeScript types at runtime.

That means you can write code like this:

ts
type User = { name: string; age: number }
const user: User = await getDoc(docRef).then((doc) => doc.data() as User)

But if Firestore contains { name: "Alice" }, you won’t know until much later that age is missing.

This can lead to subtle bugs and runtime errors.

FirestoreDataConverter

Create a new project:

ts
deno run -A npm:create-vite@latest zod-firebase --template react-ts --allow-scripts
cd zod-firebase
deno install --allow-scripts --node-modules-dir --npm firebase tailwindcss @tailwindcss/vite

Zod lets you define runtime schemas that mirror your TypeScript interfaces.

ts
import { z } from 'zod'

export const UserSchema = z.object({
  name: z.string(),
  age: z.number(),
})
export type User = z.infer<typeof UserSchema>

Pending

  • https://medium.com/@glorat/type-safe-firestore-with-typescript-and-zod-3ca9b0d05958

Estàs llegint una vista prèvia.

Inicia sessió amb Google per llegir la pàgina completa.

Inicia sessió amb Google

Amb qualsevol compte de Google. Només et demanarem que acceptis les condicions del servei.