New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

zod-class

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

zod-class

Create classes from Zod Object schemas all in one line

  • 0.0.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
29K
increased by2.27%
Maintainers
1
Weekly downloads
 
Created
Source

zod-class

This is a small utility library to accompany Zod to enable for Types and Schemas to be defined in one line by creating a Class.

Installation

npm install zod-class

Usage

import z from "zod";
import { ZodClass } from "zod-class";

export class HelloSchema extends ZodClass({
  key: z.string(),
}) {}

const hello = new HelloSchema({
  key: "key",
});

Why?

It can be annoying to always have redundant declarations for types and schemas:

  1. the z.object declaration
  2. the derived type using z.infer
interface HelloSchema extends z.infer<typeof HelloSchema> {}
const HelloSchema = z.object({
  key: z.string(),
});

zod-class enables this to be achieved in a single line.

It also provides a class that can be instantiated and methods added to.

export class Person extends ZodClass({
  firstName: z.string(),
  lastName: z.string(),
}) {
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

Caveats

Caveat: the static HelloSchema.parse's return type does not accurately reflect that it returns an instance of the created class,

const unknownValue: unknown;

// we wish it was `HelloSchema`, not `{ key: string }`.
const hello2: {
  key: string;
} = HelloSchema.parse(unknownValue);

Workaround: just cast it

// option 1
const hello: HelloSchema = HelloSchema.parse(unknownValue);

// option 2
const hello = HelloSchema.parse<HelloSchema>(unknownValue);

FAQs

Package last updated on 01 Feb 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc