Skip to content

.parse() Typescript linter accepts anything (string, number...) #1892

Closed

Description

@sneko

Hi,

I didn't find someone having my issue so I'm probably doing something wrong but... I can't figure the solution out.

Let's say I have:

const TestSchema = z.object({
  email: z.string(),
});

TestSchema.parse('hello');

The last line will not throw an error with the Typescript whereas when hovering the parse function I can see:

(method) ZodType<{ email: string; }, ZodObjectDef<{ email: ZodString; }, "strip", ZodTypeAny>, { email: string; }>.parse(data: unknown, params?: Partial<z.ParseParams> | undefined): {
    email: string;
}

Note that I use strict: true in my tsconfig.json (and at runtime, zod throws an error obviously).

A "workaround" would be to always do this:

const TestSchema = z.object({
  email: z.string(),
});
type TestSchemaType = z.infer<typeof TestSchema>;

TestSchema.parse(<TestSchemaType>'hello');

... but it's pretty verbose and annoying.

Any idea what's the issue to get the linter working normally?

Thank you,

EDIT: it seems a solution would be to use

const typedParse = <Schema extends z.ZodSchema> (
  schema: Schema, data: z.infer<Schema>
): z.infer<Schema> => schema.parse( data )

typedParse(ATest, 'hello');

(ref: #1748 (comment))

... but I don't get why this is not used by default?

Activity

  1. JacobWeisenburger commented on Jan 16, 2023

    @JacobWeisenburger
    Contributor

    Any idea what's the issue to get the linter working normally?

    What do you mean by 'normally'?


    but I don't get why this is not used by default?

    #1748 (comment)


    const typedParse = <Schema extends z.ZodSchema> (
      schema: Schema, data: z.infer<Schema>
    ): z.infer<Schema> => schema.parse( data )
    
    typedParse(ATest, 'hello');

    Another way you can solve this problem:

    type TypedParseSchema<Schema extends z.ZodSchema> = Omit<Schema, 'parse'> & {
        parse ( data: z.infer<Schema> ): z.infer<Schema>
    }
    const useTypedParse = <Schema extends z.ZodSchema>
        ( schema: Schema ): TypedParseSchema<Schema> => schema
    
    const schemaWithTypedParse = useTypedParse( z.object( {
        email: z.string(),
    } ) )
    
    schemaWithTypedParse.parse( 'hello' )
    //                          ^^^^^^^
    // Argument of type 'string' is not assignable to parameter of type '{ email: string; }'.

    Would this work for you?

  2. Repository owner locked and limited conversation to collaborators on Jan 16, 2023
  3. converted this issue into a discussion #1894 on Jan 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions