Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using undefined instead of null for optional fields in prisma-client-js

I am using Prisma with MongoDB, and I have a model with optional fields as shown below in TypeScript:


model user {
    id         String     @id @default(auto()) @map("_id") @db.ObjectId
    username   String
    password   String
    name       String?
    surname    String?
}

The resulting generated TypeScript type for the 'user' model is:


export declare type User = {
    id: string
    username: string
    password: string
    name: string | null
    surname: string | null
}

The issue arises when attempting to check for type overlap between the generated 'User' type and another type I am using. This other type is also generated, but it comes from another package, and I do not have the flexibility to modify it. As a result, an error is thrown during the type check.

I have tries to find a solution for this problem, but unfortunately, I could not find any helpful resources or suggestions.

My final question is: Is there a way to specify to prisma-client-js to use undefined for optional fields, or is there a method to modify the way it generates TypeScript types for optional fields?

like image 493
InsalataCondita Avatar asked Oct 16 '25 07:10

InsalataCondita


1 Answers

I don't think it's possible, but there is a workaround, you can use Prisma.UserCreateInput or Prisma.UserCreateManyInput:

import { Prisma } from '@prisma/client';

// It's a bit of a hack though
type UserOptional = Prisma.UserCreateManyInput

Or you can use TypeScript to create a new type out of User, e.g. using this answer How to make nullable properties optional in TypeScript?:

type PickNullable<T> = {
  [P in keyof T as null extends T[P] ? P : never]: T[P]
}

type PickNotNullable<T> = {
  [P in keyof T as null extends T[P] ? never : P]: T[P]
}

type OptionalNullable<T> = {
  [K in keyof PickNullable<T>]?: Exclude<T[K], null>
} & {
  [K in keyof PickNotNullable<T>]: T[K]
}

type UserOptional = OptionalNullable<User>
like image 132
Danila Avatar answered Oct 18 '25 22:10

Danila