prisma-json-types-generator

Using this package? Please consider donating to support my open source work ❤️


Issues Stars License Downloads Bundlephobia Packagephobia

⚒️ Prisma Json Types Generator

A generator that changes the Prisma Client output to strongly type Json fields



// schema.prisma

generator client {
  provider = "prisma-client-js"
}

/// Always after the prisma-client-js generator
generator json {
  provider = "prisma-json-types-generator"
  // namespace = "PrismaJson"
  // clientOutput = "<finds it automatically>"
  // (./ -> relative to schema, or an importable path to require() it)
}

model Example {
  /// [MyType]
  normal Json

  /// [MyType]
  optional Json?

  /// [MyType]
  array Json[]
}
// index.ts

import type { Example } from '@prisma/client';

declare global {
  namespace PrismaJson {
    // you can use classes, interfaces, types, etc.
    type MyType = boolean;
  }
}

function myFunction(example: Example) {
  // example.normal   is now a boolean
  // example.optional is now a boolean | null
  // example.array    is now a boolean[]
}

How it works

⚠️ It just changes the declaration files of your generated client, no runtime code is affected!

By using the Typescript Compiler API, this generator parses the generated client’s types AST and looks for Prisma.JsonValue types (or related) and replaces them with their corresponding type.

Some types are still json!

There are some complex json types like JsonFilter and JsonWithAggregatesFilter that, if typed, would impact the usability of the client. So, they are still json.

declare global is not working!

Using declare global in a file that is not a module (that is contains no import/export) is an error since everything in such a file is in the global scope anyway. You can either remove it or add an empty export {} to make it a module.

Limitations