Skip to content

Define type of content of Json field #3219

@MaximNd

Description

@MaximNd

Problem

Right now if you have the following schema with Json field:

model User {
  id               Int  @default(autoincrement()) @id
  name             String?
  extendedProfile  Json
}

You'll end up with a problem that you don't have strict type for extendedProfile field in .ts.

const user = prismaService.user.findOne(...);
user.extendedProfile // we don't know the type of extendedProfile

The one way to fix it, is specify some interface in your code and use it like this:

interface UserProfile {
    field1: string;
    field2: number;
}

const user = prismaService.user.findOne(...);
(user.extendedProfile as UserProfile).field1; // now we have autocompletion

But it's not really comfortable to use it like that each time.

Also we can create some class and create instance of it like that:

interface UserProfile {
    field1: string;
    field2: number;
}

class User {
    id: string;
    name?: string;
    extendedProfile: UserProfile;

    constructor(user: PrismaUser /* user object returned by prisma */) {
        // ... initialize
    }
}

const user = new User(prismaService.user.findOne(...));

But this solution creates some overhead due to the creation of an additional object.

Suggested solution

Maybe we can specify type in schema.prisma file like that?

json ExtendedUserProfileJson {
    field1  String
    field2  Int
}

model User {
  id               Int  @default(autoincrement()) @id
  name             String?
  extendedProfile  ExtendedUserProfileJson
}

Alternatives

Alternatively, we can somehow manage this in the typescript.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions