Function: createSafeModel()
createSafeModel<
S
,E
>(schema
,extend?
): { [KeyType in string | number | symbol]: ({ [Key in keyof SafeModel<S> as Key extends keyof E ? never : Key]: SafeModel<S>[Key] } & E)[KeyType] }
Defined in: packages/model/src/safe.ts:37
Creates a safe model where all validation methods return Result types instead of throwing errors. Replaces the default from
and cast
methods with safe versions.
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 SafeModel<S> as Key extends keyof E ? never : Key]: SafeModel<S>[Key] } & E)[KeyType] }
A model with safe validation methods that return Result types
Example
import { z } from 'zod';
import { isOk } from '@uni-ts/result';
type User = InferModelOutput<typeof User>; // { name: string; email: string }
const User = createModel(z.object({
name: z.string().min(1),
email: z.string().email(),
}));
const result = User.from({ name: '', email: 'invalid' });
if (isOk(result)) {
console.log('Valid user:', result.value);
} else {
console.log('Validation issues:', result.error);
}