[英]Typescript not detecting Prisma optional fields
我正在為我的 NestJS 項目創建種子文件,但 typescript 不會編譯,因為它沒有檢測到某些字段在 Prisma Client 中是可選的。
這是 model 的示例,我遇到以下問題:
model Company {
companyId Int @id @default(autoincrement())
name String
address String?
email String?
isActive Boolean @default(true)
managers CompanyUser[]
locations Location[]
}
然后我嘗試制作一系列公司,如下所示:
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);
}
});
};
但是我收到以下錯誤: Type '{ companyId: number; name: string; }' is missing the following properties from type 'Company': address, email, isActivets(2739)
Type '{ companyId: number; name: string; }' is missing the following properties from type 'Company': address, email, isActivets(2739)
由於這些字段是可選的或已經有默認選項,我該怎么做才能讓它通過?
Prisma 為每個 model 生成多個變體類型,包括select
和update
arguments 的變體類型。
在您的情況下,您必須使用生成的類型CompanyCreateInput
而不是Company
:
import { Prisma } from '@prisma/client';
const companies: Array<Prisma.CompanyCreateInput> = [
{
companyId: 1,
name: "The Best Gym Ever",
},
];
Prisma 為Company
生成的類型包括所有屬性,但允許可選字段為 null。
這就是 Prisma 保持代碼清潔和類型安全的全部方式。 查看它們生成的類型,您會看到一種模式。 在你的情況下比較這些:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.