I am working on creating a function that displays a specific Prisma model based on the model name provided as a parameter. The challenge is to ensure that TypeScript can verify if the specified model actually exists each time.
/*
file schema.prisma models:
model User {
id Int @id @default(autoincrement())
name String
password String
job String @default("")
location String @default("")
phone String @default("")
email String
}
model Participant {
id Int @id @default(autoincrement())
userID Int
groupID Int
}
*/
import { PrismaClient } from "@prisma/client";
function loadModel(modelName: /* string */) {
const prisma = new PrismaClient();
const Model = prisma[modelName]
}
loadModel("user")
An error occurs with the following code:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'. No index signature with a parameter of type 'string' was found on type 'PrismaClient<PrismaClientOptions, never, RejectOnNotFound | RejectPerOperation | undefined>'.
To address this issue, I attempted adding : keyof PrismaClient
to the modelName parameter. While this resolved the initial error, I encountered a new problem when trying to use functions like Model.create({...}):
Property 'create' does not exist on type '(<V extends "beforeExit">(eventType: V, callback: (event: V extends "query" ? QueryEvent : V extends "beforeExit" ? () => Promise : LogEvent) => void) => void) | ... 11 more ... | MessageDelegate<...>'. Property 'create' does not exist on type '<V extends "beforeExit">(eventType: V, callback: (event: V extends "query" ? QueryEvent : V extends "beforeExit" ? () => Promise : LogEvent) => void) => void'.
What steps should I take to resolve this issue?