Using prisma and typescript models in parallel

Viewed 1401

I often use const assertions in my typescript models:

const ListingVehicleTypes = [
  "car",
  "motorcycle",
  "caravan",
  "camper_trailer"
] as const;

interface LISTING {
  vehicleType: typeof ListingVehicleTypes[number];
  ...
}

As such, LISTING["vehicleType"] is correctly inferred as "car" | "motorcycle" | "caravan" | "camper_trailer".

Can I express such restrictions in my schema.prisma? Neither imports nor typescript utils are allowed in *.prisma files:

model Listing {
    vehicleType   typeof ListingVehicleTypes[number]  // no-go
}

If not, is there a way to "enrich" the prisma models with the type-safer typescript models when prisma-powered DB queries are performed?

I can always cast the query bodies and responses to any but is there a cleaner approach?

For what it's worth, I'm using the mongodb provider -- but I don't think the provider plays a role here.

1 Answers

I suggest using an enum for this. But make sure to check if enums are supported in the underlying database from here.

In Prisma schema,


model Listing {
  vehicleType  VehicleType @default(car)
}

enum VehicleType {
  car
  motorcycle
  caravan
  camper_trailer
}

Then in your typescript code you can utilize this as follows.

import { Listing } from "@prisma/client";

type VehicleTypes = Listing["vehicleType"];

Related