Thanks to visit codestin.com
Credit goes to github.com

Skip to content

strict object instead of strip #21

@cyrilchapon

Description

@cyrilchapon

For a specific use-case (POST http handling), I'd want to throw (strict) instead of removing unallowed keys (strip), and I'd want tozod to hint me for the type.

Example, currently this is working :

const restrictedFields = ['id'] as const
type RestrictedField = typeof restrictedFields[number]
type OmitRestrictedFields<T> = Omit<T, RestrictedField>

type User = {
  id: string,
  nickName: string
}

type UserCreationPayload = OmitRestrictedFields<User>

type UserCreationPayloadZ = toZod<UserCreationPayload> = z.object({
  nickName: z.string()
})

but the fact tozod uses strip allows this :

type UserCreationPayloadZ = toZod<UserCreationPayload> = z.object({
  id: z.string(), // This typechecks OK
  nickName: z.string()
})

which is sort of OK in many cases; because strip default behavior of zod will remove id runtime anyway.


BUT I'd want this reflected in typing system, disallowing completely id and hinting myself about that. The way to go would be to .strict() the schema; but tozod disallows this.

type UserCreationPayloadZ = toZod<UserCreationPayload> = z.object({
  id: z.string(),
  nickName: z.string()
}).strict()
// This typechecks wrong with "Impossible to assign type '"strict"' to type '"strip"'.ts(2322)"

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