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

Union with null for optional fields #21

Open
davevanfleet opened this issue Jan 21, 2025 · 0 comments
Open

Union with null for optional fields #21

davevanfleet opened this issue Jan 21, 2025 · 0 comments

Comments

@davevanfleet
Copy link

Please consider supporting me for faster fixes, responses and features Sponsor Me

Problem

When optional fields in the prisma schema are null, the prisma client will explicitly return null from the model query methods. By decorating class properties with @IsOptional(), with the type as someField?: string (as opposed to someField?: string | null), we receive typescript errors such as type string | undefined is not assignable to type string | null.

Suggested solution

When a field in the schema has isRequired = false, append " | null" to the type generated for the class. The resulting generated class would then be defined this way:

export class SomeModel {
    @IsDefined()
    @IsInt()
    requiredField!: number;

    @IsOptional()
    @IsInt()
    optionalField?: number | null;

    @IsOptional()
    @IsString()
    anotherOptionalField?: string | null;
}

Alternatives

Additional context

I am trying to use this generator as a way of creating classes that can be used in NestJS controllers where an OpenAPI schema is generated. I would like to generate as much code as possible, and this generator seems to fit my needs in all ways except in how it handles creating the type definitions for optional fields.

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

1 participant