Carlos Gonzalez
Carlos Gonzalez

Reputation: 111

Typescript not detecting Prisma optional fields

I'm creating seed files for my NestJS project, but typescript won't compile because it doesn't detect some fields are optional from the Prisma Client.

This is an example of a model I'm having issues with:

model Company {
  companyId Int           @id @default(autoincrement())
  name      String
  address   String?
  email     String? 
  isActive  Boolean       @default(true)
  managers  CompanyUser[]
  locations Location[]
}

Then I try to make an array of Companies, something like this:

import { Company, PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

const companies: Array<Company> = [
  {
    companyId: 1,
    name: "The Best Gym Ever",
  },
];

export const locationsSeed = async () => {
  companies.forEach(async (company) => {
    try {
      await prisma.company.create({
        data: company,
      });
    } catch (e) {
      console.error(e);
    }
  });
};

But I'm getting the following error: Type '{ companyId: number; name: string; }' is missing the following properties from type 'Company': address, email, isActivets(2739)

What can I do to make it pass since these fields are optional or have default options already?

Upvotes: 4

Views: 2562

Answers (2)

Betzabe Silva
Betzabe Silva

Reputation: 1

I had a similar problem. But think of it in this way, if you are describing a Company type (something that is supposed to be created already in your database) you should have those properties, even if they are null values.

Something you can do is to add those properties... address: null, email:null

Otherwise, if you want it to be created, (as is your case) you should use a CreateCompanyDto, another type to manage the required properties to create a Company.

Upvotes: 0

Kyle Cureau
Kyle Cureau

Reputation: 19366

Prisma generates several variant types of each model including those for select and update arguments.

In your case, you'd have to use the generated type CompanyCreateInput instead of Company:

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

const companies: Array<Prisma.CompanyCreateInput> = [
  {
    companyId: 1,
    name: "The Best Gym Ever",
  },
];

The types generated by Prisma for Company include all properties but allow optional fields to be null.

This is all Prisma's way of keeping your code clean and type safe. Look at their generated types and you'll see a pattern. In your case compare these:

export type Company = {
  id: string
  optionalField: string | null
}
export type CompanyCreateInput = {
  id: string
  optionalField?: string | null
}
export type CompanyUpdateInput = {
    id?: StringFieldUpdateOperationsInput | string
    optionalField?: NullableStringFieldUpdateOperationsInput | string | null
}

Upvotes: 2

Related Questions