Typescript is making me pass an id even though it is a bigserial and it should increment by itself

Viewed 551

I am using Prisma 2 as my ORM and it is generating a typescript type for me along with the migration. The problem is that the id field (with the @id decorator) has to be required and so that translates into TS and the compiler makes me pass in the id. But the id is a bigint and so it should increment itself. I have already tried altering the type manually but then I have to rewrite it every time i migrate. I already have the same schema on one other model and that works just fine. I can't seem to figure out why

my schema.prisma User model:

model User {
  id            Int     @id @unique @default(autoincrement())
  first_name    String   @db.VarChar(20)
  middle_name   String?  @db.VarChar(20)
  last_name     String   @db.VarChar(50)
  email         String?  @db.VarChar(50)
  date_of_birth DateTime @db.Date
  posts         Post[]
  password      String
  sessionSecret String 
}
2 Answers

The Prisma types are generating exactly what the Model has defined in it. The model has id as required, so the generated type has the id property required.

You have two simple options around this. Modify the Prisma type to make the id optional, or create a second TypeScript interface with an optional id or without the id property.

Option One

Based on the docs, https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference/#-modifier-1, the modified Prisma type would look like this,

model User {
  id?            Int     @id @unique @default(autoincrement())
  ...rest of the model

Option Two

If the existing TypeScript interface is this,

interface User {
  id: number;
  first_name: string;
  ...rest of the interface
}

then your modified TypeScript interface without the id property could be,

interface NewUser extends Omit<User, 'id'> {}

Or with an optional id property,

interface NewUser extends Omit<User, 'id'> {
  id?: number;
}

I also encountered this problem and realised it was caused by using the wrong types. I had a user model with

id            Int        @id(map: "mood_pk") @default(autoincrement())

which results in a User type with

id: number,

however when calling prisma.user.create({data: newUser}), the newUser object should not be typed with User, it should be typed with Prisma.userCreateInput, which does not require that a number is passed to the id prop.

Just adding this here in case it helps anyone else, and for next time I forget this and run into the same issue...

Related