decs / typeschema

🛵 Universal adapter for TypeScript schema validation.
https://typeschema.com
MIT License
368 stars 11 forks source link

@typeschema/main doesn't infer the type of zod object correctly #63

Open Melvynx opened 1 month ago

Melvynx commented 1 month ago

Today I try this code :

import { Infer, Schema } from '@typeschema/main';

const ZodSchema = z.object({
  title: z.string(),
});

type ZodSchemaType = z.infer<typeof ZodSchema>;

type Output = Infer<typeof ZodSchema>;

CleanShot 2024-08-06 at 22 04 52

But the type of output is any, when I replace @typeschema/main by @typeschema/zod the error is fixed.

The documentation is very small, is this a feature or a bug ?

Upvote & Fund

Fund with Polar

sebastianwessel commented 2 weeks ago

Same issue and it is kind of blocking development @puristajs

Hope, it gets solved soon

sebastianwessel commented 2 weeks ago

Seems not to be zod specific:

import type { Infer } from "@typeschema/main";
import {object,string} from 'yup'

const yupSchema = object({ 
  optionOne: string().required()
})

type test= Infer<typeof yupSchema>
// test = unknown
sebastianwessel commented 2 weeks ago

@decs

The root cause of this issue is, that the lib is using @sinclair/typebox, which is missing in the package dependencies.

Without this dependency, IsTypeboxSchema returns true, even if it is a zod or yup schema, which results in a wrong Select with typebox instead of zod or yup.

export type Select<TSchema> =
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  TSchema extends Function
    ? TSchema extends {assert: unknown} ? 'arktype'
    : IsEffectSchema<TSchema> extends true ? 'effect'
    : IsClassValidatorSchema<TSchema> extends true ? 'classValidator'
    : 'function'
  : TSchema extends object
    ? IsTypeboxSchema<TSchema> extends true ? 'typebox'
    : IsSuretypeSchema<TSchema> extends true ? 'suretype'
    : TSchema extends {__isYupSchema__: unknown} ? 'yup'
    : TSchema extends {_def: unknown} ? 'zod'
    : TSchema extends {async: unknown} ? 'valibot'
    : TSchema extends {refiner: unknown} ? 'superstruct'
    : TSchema extends {_flags: unknown} ? 'joi'
    : TSchema extends {encode: unknown} ? 'ioTs'
    : TSchema extends {reflect: unknown} ? 'runtypes'
    : TSchema extends {kind: unknown} ? 'deepkit'
    : TSchema extends {addValidator: unknown} ? 'ow'
    : TSchema extends {toTerminals: unknown} ? 'valita'
    : TSchema extends {bail: unknown} ? 'vine'
    : IsJSONSchema<TSchema> extends true ? 'json'
    : 'fastestValidator'
  : never;

Package suretype is also used, but seems not to be in deps as well.

@Melvynx The temporary workaround/fix is, to manually add the missing dep. npm i -D @sinclair/typebox