Skip to content

Function: createModel()

createModel<S, E>(schema, extend?): { [KeyType in string | number | symbol]: ({ [Key in keyof Model<S> as Key extends keyof E ? never : Key]: Model<S>[Key] } & E)[KeyType] }

Defined in: packages/model/src/index.ts:39

Creates a type-safe data model based on schema from any Standard Schema compatible validation library.

Type Parameters

S

S extends StandardSchemaV1<unknown, unknown>

Type of the Standard Schema compatible validation schema

E

E extends Record<PropertyKey, unknown> = { }

Parameters

schema

S

A validation schema that follows the Standard Schema interface

extend?

E

Returns

{ [KeyType in string | number | symbol]: ({ [Key in keyof Model<S> as Key extends keyof E ? never : Key]: Model<S>[Key] } & E)[KeyType] }

A model object with validation utilities

Examples

typescript
import { z } from 'zod';

type User = InferModelOutput<typeof User>; // { name: string; email: string }
const User = createModel(z.object({
  name: z.string().min(1),
  email: z.string().email(),
}));

const user1  = User.from({ name: 'John', email: '[email protected]' }); // User
const user2 = User.from({ name: '', email: '' }); // throws ModelValidationError
typescript
import { z } from 'zod';

type Email = InferModelOutput<typeof Email>; // string & z.$brand<'Email'>
const Email = createModel(z.string().email().brand('Email'));

function sendEmail(email: Email) {
  // TypeScript ensures only validated emails can be passed
}