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

Handling of 'readonly' and 'Readonly<>' #191

Open
RopoMen opened this issue Dec 7, 2023 · 3 comments
Open

Handling of 'readonly' and 'Readonly<>' #191

RopoMen opened this issue Dec 7, 2023 · 3 comments
Labels
enhancement New feature or request

Comments

@RopoMen
Copy link

RopoMen commented Dec 7, 2023

Bug description

Why ts-to-zod is not adding .readonly() for attributes or objects? I noticed that tests are now expecting that it fallbacks to the default type, why so?

Is there some issues with readonly? Zod objects themselves seems to make it trivial to use.

Input

Case 1

type Settings = {
  readonly foo: string
}

Case 2

type Settings = Readonly<{
  foo: string
}>

Expected output

Case 1

const testSettingsSchema = z.object({
    foo: z.string().readonly()
});

Case 2

const testSettingsSchema = z.object({
    foo: z.string().readonly() // not sure if this is needed because object has .readonly()
}).readonly();

Actual output

Case 1

const testSettingsSchema = z.object({
    foo: z.string()
});

Case 2

const testSettingsSchema = z.object({
    foo: z.string()
});
@RopoMen
Copy link
Author

RopoMen commented Dec 7, 2023

Only references into "readonly" in ts-to-zod codebase

@schiller-manuel
Copy link
Collaborator

zod's readonly support was added in August 2023 (see https://github.com/colinhacks/zod/releases/tag/v3.22.0) while the code you found is from 2021, so that probably explains why 😄

I looked at a few variations with z.infer:

Screenshot 2023-12-08 at 00 19 13

I also found this zod issue: colinhacks/zod#2732

So it looks like we cannot (yet?) generate a schema that correctly represents the typescript type.

@RopoMen
Copy link
Author

RopoMen commented Dec 8, 2023

It definitely explains :)

I also noticed that issue with single property case. I was thinking that could that readonly() (Object.freeze() I think) applied to object properties which are wrapped using Readonly<>?

I would think that any improvement into this is good, even if that cannot be implemented fully until zod fixes its issues.

@tvillaren tvillaren added the enhancement New feature or request label Mar 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants