Skip to content

Typescript Snippets

Use zod.refine() to validate confirmation

typescript
const profileSchema = z
  .object({
    myNumber: z.number(),
    confirmMyNumber: z.number(),
  })
  .refine(data => data.myNumber === data.confirmMyNumber, {
    message: 'Oops, myNumber does not match its confirmation',
  });

const result = profileSchema.safeParse({
  myNumber: 3,
  confirmMyNumber: 5,
});

if (!result.success) {
  console.log(result.error);
} else {
  console.log(result);
}

Zod with OpenApi

typescript
import { z } from 'zod';
import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';

extendZodWithOpenApi(z);

const tenantSchema = z.object({
  userName: z.string(),
  tenantNane: z.string(),
  status:
});

const tenantSchemaWithOpenApi = tenantSchema.openapi({
  example: {
    userName: 'louis',
    tenantNane: 'bagubagu',
    status: 'active'
  }
});

type Tenant = z.infer<typeof tenantSchema>;

Import a JSON file

tsconfig.json

json
{
  "compilerOptions": {
    // ... other options
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}

typescript

typescript
import emp from './employee.json';

type Employee = { id: number; name: string; salary: number };

const employee = emp as Employee;
console.log(employee.name.toUpperCase());

The json file imported must be under rootDir.

Made with ❤️ by Bagubagu Studio