This is a very simplified case, I have more advanced cases. I have defined a "payment" model in my schema like this:
model Payment {
id Int @default(autoincrement()) @id
covered Boolean?
paid Boolean
amount number
}
Doing const payments = Payment.findMany
with all properties selected, this gives us a type of this:
type Payment = {
id: number;
covered?: boolean;
paid: boolean;
amount: number;
}
However I want to tell Prisma that findMany
should actually return this below. In below, covered is non-null in case of paid
being true
:
type Payment = {
id: number;
amount: number;
} & (
| { paid: false; covered?: never }
| { paid: true; covered: boolean }
)
Is it possible to tell Prisma this refined type hint somehow? I tried this in the code below:
const payments = await prisma.payment.findMany(.....) as Omit<typeof payments[number], 'paid' | 'covered'> & (
| { paid: false; covered?: never }
| { paid: true; covered: boolean }
);
I think your best bet is to use what's called "discriminant type" using a common property, in your case paid
property like this. Here's the link to the playground for your reference
interface BasePayment {
id: number;
paid: boolean;
amount: number;
}
interface PaidPayment extends BasePayment {
paid: true;
covered: boolean;
}
interface UnpaidPayment extends BasePayment {
paid: false;
}
const paidPayment: PaidPayment = {
id: 1,
amount: 10,
covered: true,
paid: true
};
const unpaidPayment: UnpaidPayment = {
id: 1,
amount: 10,
covered: true, // This won't compile because type `UnpaidPayment` doesn't have `covered`
paid: false
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.