Skip to content

Instantly share code, notes, and snippets.

@iskenxan
iskenxan / order-matters.ts
Created January 17, 2022 14:36
Typescript schema validation with zod
z.string().optional().array(); // (string | undefined)[]
z.string().array().optional(); // string[] | undefined
@iskenxan
iskenxan / safe-parse.ts
Created January 17, 2022 14:35
Typescript schema validation with zod
mySchema.safeParse(""I am a valid password""); // => { success: true; data: "I am a valid password" }
mySchema.safeParse(""); // => { success: false; error: ZodError }
@iskenxan
iskenxan / objects-client.ts
Created January 17, 2022 14:34
Typescript schema validation with zod
const result = User.parse({
email: "[email protected]",
name: "Hello World"
});
@iskenxan
iskenxan / objects-example-error.ts
Created January 17, 2022 14:33
Typescript schema validation with zod
[
{
"code": "invalid_type",
"expected": "number",
"received": "undefined",
"path": [
"phoneNumber"
],
"message": "Required"
}
@iskenxan
iskenxan / objects-example.ts
Created January 17, 2022 14:32
Typescript schema validation with zod
import { z } from "zod";
const User = z.object({
email: z.string().email(),
name: z.string(),
phoneNumber: z.number()
});
@iskenxan
iskenxan / zod-error.ts
Created January 17, 2022 14:31
Typescript schema validation with zod
[
{
"code": "too_small",
"minimum": 1,
"type": "string",
"inclusive": true,
"message": "Should be at least 1 characters",
"path": []
},
{
@iskenxan
iskenxan / basic-example.ts
Created January 17, 2022 14:30
Typescript schema validation with zod
import { z } from "zod";
const stringSchema = z.string().nonempty().min(8).max(32);
stringSchema.parse("");
stringSchema.parse(""); // throws an exception
stringSchema.parse("I am a valid password"); // returns "I am a valid password"
@iskenxan
iskenxan / composing-schemas-zod.ts
Created January 17, 2022 14:29
composing-schemas-zod.ts
const User = z.object({
email: z.string().email(),
name: z.string(),
phoneNumber: z.number()
});
const Hobby = z.object({
hobbyName: z.string().min(1)
});
const Hobbyist = User.merge(Hobby);
const result = Hobbyist.safeParse({
@iskenxan
iskenxan / basic-example.ts
Created January 17, 2022 14:27
Typescript schema validation with zod
import { z } from "zod";
const stringSchema = z.string().nonempty().min(8).max(32);
stringSchema.parse("");
stringSchema.parse(""); // throws an exception
stringSchema.parse("I am a valid password"); // returns "I am a valid password"
import React, { Suspense } from "react";
import { GET_LAUNCHES } from "./queries";
import { useAPI } from "./useAPI";
const Launches = ({ launches }) => {
return (
<div>
{launches.read().launchesPast.map((item) => (
<div>
<h1>{item.mission_name}</h1>