Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting typeName in custom types #2917

Closed
defrex opened this issue Oct 30, 2023 · 4 comments
Closed

Allow setting typeName in custom types #2917

defrex opened this issue Oct 30, 2023 · 4 comments

Comments

@defrex
Copy link

defrex commented Oct 30, 2023

I'm using a custom type for Decimal.js fields like so

const decimal = z.custom<Decimal>(Decimal.isDecimal)

This is nice and simple, which is great!

However, when building a UI based on an arbitrary zod-typed input, I use _def.typeName to determine the expected output type for the sake of formatting, etc. Currently custom fields are labeled as ZodEffects, which isn't particularly helpful.

Something like this would be great

const decimal = z.custom<Decimal>(Decimal.isDecimal, { typeName: 'ZodDecimal' })

Alternatively, a custom metadata solution as described in #273 would also enable me to solve the problem.

@rotu
Copy link
Contributor

rotu commented Nov 7, 2023

Maybe it would be better to use a Map (or WeakMap) to keep track of this.

const customTypeName = new Map()

const decimal = z.custom<Decimal>(Decimal.isDecimal)
customTypeName.set(decimal._def, "Decimal")

function getExtendedTypeName(someZodType){
  return customTypeName.get(someZodType._def) ?? someZodType._def.typeName;
}

@baloodevil
Copy link

I have the same need; I'm showing UI controls based on the typeName. But when I changed a property from a ZodDate to a z.custom... the typeName becomes ZodAny so I don't know to show a date picker in the UI.

@defrex
Copy link
Author

defrex commented Jan 3, 2024

Maybe it would be better to use a Map (or WeakMap) to keep track of this.

It definitely feels worse to me to require an extra data structure taped to the side of Zod in order to track what type a field is, since Zod is supposed to be the source of truth for the schema.

I sortof understand the stance on custom metadata, but tracking type information feels like something Zod should support, IMO.

@colinhacks
Copy link
Owner

Currently z.custom is actually just syntactic sugar over z.any().refine(). If you're relying on typeName or other internals, it's better to define a subclass of ZodType.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants