npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

prisma-json-types-generator

v6.0.0

Published

Changes JsonValues to your custom typescript type

Readme

[!IMPORTANT]
prisma-json-types-generator@6 supports Prisma 7.10 or later and does not depend on your project's TypeScript version. See Legacy versions for older releases.

Your own TypeScript types for the Json and scalar fields of the Prisma client.

Prisma types every Json field as JsonValue and every String field as string. This generator replaces those types in the generated @prisma/client with TypeScript types you define, so the compiler checks the values you read and write.

It works with every database Prisma supports. Only the generated types change, so there is no runtime cost.

Features

  • Object shapes for Json fields, including Json[] lists.
  • Literal unions for String, Int and Float fields, which gives you enums without native database enums.
  • Types declared in a global namespace or written inline in the schema.
  • Support for several @prisma/client generators at once, useful while moving the client to a new output location.

Installation

npm install -D prisma-json-types-generator

Install the skill

An agent skill for this generator is also available:

npx skills add arthurfiorette/prisma-json-types-generator

It teaches AI agents to set up the generator and to type Prisma Json, String, Int and Float fields with the /// [Type] and /// ![Type] syntax.

Configuration

Options go in the generator block of schema.prisma:

generator json {
  provider  = "prisma-json-types-generator"
  namespace = "PrismaJson"
  allowAny  = false
  // etc...
}

| Option | Description | Default | | :--------------- | :---------------------------------------------------------------------------------------------------------------------------------------------- | :--------------- | | namespace | Global namespace that holds your custom types. | "PrismaJson" | | clientOutput | Path to the @prisma/client output directory. It is detected automatically, so set it only when detection fails, as in some monorepos. | (auto-detected) | | allowAny | When true, untyped Json fields resolve to any instead of unknown. | false | | useType | Type in your namespace used for every untyped Json field. The generator adds an index signature [key: string]: any to it. | undefined | | typedSqlUrlEnv | Environment variable with the PostgreSQL URL used to match TypedSQL columns to schema fields. | "DATABASE_URL" | | typedSqlPath | Directory of your TypedSQL .sql files, relative to the schema. Set it only if you changed typedSql.path in prisma.config.ts. | "sql" |

Quick start

  1. Add the generator to your schema

    Add a json generator block after the client generator in schema.prisma.

    generator client {
      provider = "prisma-client"
    }
    
    generator json {
      provider = "prisma-json-types-generator"
    }
  2. Declare your types

    Create a declaration file such as src/types.ts, make sure your tsconfig.json includes it, and declare your types in the global PrismaJson namespace.

    // declare global only works inside a module, hence the empty export.
    export {};
    
    declare global {
      namespace PrismaJson {
        type UserProfile = {
          theme: 'dark' | 'light';
          twitterHandle?: string;
        };
      }
    }
  3. Link the types in your schema

    Add a /// [TypeName] AST comment above a Json field to give it that type.

    model User {
      id    Int    @id @default(autoincrement())
      email String @unique
    
      /// [UserProfile]
      profile Json
    }

Run npx prisma generate and User.profile is typed as PrismaJson.UserProfile:

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

async function updateUserProfile() {
  const user = await prisma.user.update({
    where: { id: 1 },
    data: {
      profile: {
        theme: 'dark'
        // twitterHandle is optional
      }
    }
  });

  // user.profile is PrismaJson.UserProfile
  console.log(user.profile.theme); // 'dark'
}

Typing String fields (enums)

String fields can be typed as a union of string literals, which works as an enum without Prisma's native enum type and keeps the allowed values in your schema. Use the inline syntax, /// ![Type]:

model Post {
  id    Int    @id @default(autoincrement())
  title String

  /// !['draft' | 'published' | 'archived']
  status String @default("draft")
}

post.status is then typed as 'draft' | 'published' | 'archived'.

Advanced typing

A field can reference a type from the namespace or have its type written inline:

  1. /// [TypeName] references a type in the PrismaJson namespace. Use it for complex or reused types.
  2. /// ![Type] takes a TypeScript type written in the schema. Use it for small one-off types such as unions or simple objects.

Examples

model Product {
  id Int @id

  // Namespace-based type
  /// [ProductMeta]
  meta Json?

  // Array of namespace-based types
  /// [Tag]
  tags Json[]

  // Inline union type (enum)
  /// !['physical' | 'digital']
  type String

  // Numeric scalar literal unions
  /// ![1 | 2 | 3]
  priority Int

  /// ![1.5 | 2.5 | 3.5]
  weight Float

  // Inline object type
  /// ![{ width: number; height: number }]
  dimensions Json
}
export {};

declare global {
  namespace PrismaJson {
    type ProductMeta = {
      sku: string;
      stock: number;
    };

    type Tag = {
      id: string;
      name: string;
    };
  }
}

Notes:

  • On list fields such as tags Json[], annotate the element type (/// [Tag]). An array type like /// ![Tag[]] belongs on a plain Json field whose stored value is a JSON array.
  • The same syntax works on String, Int and Float fields, nullable ones included.

TypedSQL

Prisma types TypedSQL results from the database alone, so Json columns come out as JsonValue and annotated String columns as string. When you run prisma generate --sql, this generator applies your types to them as well, with both prisma-client and prisma-client-js.

Columns read from your models (PostgreSQL)

A result column that comes straight from a table column gets the type of the matching schema field, as model payloads do:

model User {
  id      Int    @id
  /// [UserProfile]
  profile Json   @map("profile_data")
  /// [UserEmail]
  email   String
}
-- prisma/sql/getUsers.sql
WITH u AS (SELECT id, profile_data AS p, email FROM "User")
SELECT u.id, u.p AS profile, u.email AS contact FROM u
export namespace getUsers {
  export type Result = {
    id: number;
    profile: PrismaJson.UserProfile; // was $runtime.JsonValue
    contact: PrismaJson.UserEmail; // was string
  };
}

The generator does not match columns by name. It asks PostgreSQL to describe the query, without running it, and PostgreSQL reports the source table and column of each result column. Aliases, joins, subqueries and CTEs are handled, and columns with the same name in different tables or schemas are kept apart. Nullability and Json[] arrays stay as Prisma inferred them.

Like prisma generate --sql itself, this needs a database connection:

  • Install pg. You already have it if you use @prisma/adapter-pg.
  • The URL is read from DATABASE_URL, or from the variable named in the typedSqlUrlEnv option. Prisma does not pass the URL from prisma.config.ts to generators.

Without a connection, the generator prints a warning and applies only the .sql annotations described below.

Annotating columns in the .sql file

Computed columns have no schema field, and databases other than PostgreSQL don't report where a column comes from. For these, add a -- comment to the .sql file with the usual syntax followed by the column name. These annotations take priority over schema field annotations:

-- prisma/sql/getStats.sql
-- [UserStats] stats
-- ![{ total: number }] "Total Count"
SELECT
  json_build_object('posts', count(*)) AS stats,
  json_build_object('total', count(*)) AS "Total Count"
FROM "Post"

As with Prisma's @param, every line starting with -- is read, so an annotation can also go next to its column. The name must match the returned column name. PostgreSQL lowercases unquoted names (AS Stats returns stats), so quote a name to keep its case.

Parameters

Put the annotation at the start of the description in Prisma's @param tag:

-- @param {Json} $1:filter [PostFilter]
-- @param {String} $2:email [UserEmail]
SELECT id FROM "Post" WHERE meta @> $1 AND author_email = $2

Parameters without an annotation keep Prisma's type.

Validating types at runtime

This generator only checks types at compile time. For runtime validation, derive the namespace types from a validation library such as Zod, so both checks come from one definition:

  1. Define the schema with Zod.
  2. Infer the TypeScript type from it.
  3. Expose that type in the PrismaJson namespace.

In schema.prisma:

model User {
  id          Int    @id @default(autoincrement())

  /// [UserPreferences]
  preferences Json
}

In your type declaration file:

import { z } from 'zod';

// 1. Define the Zod schema as the source of truth.
export const UserPreferencesSchema = z.object({
  theme: z.enum(['light', 'dark']),
  language: z.string().optional()
});

// 2. Expose the inferred type to Prisma.
declare global {
  namespace PrismaJson {
    type UserPreferences = z.infer<typeof UserPreferencesSchema>;
  }
}

Other libraries with static type inference, such as TypeBox or Yup, work the same way.

How it works

During npx prisma generate, Prisma passes the generator the Data Model Meta Format (DMMF), which contains your schema and its AST comments. Once the Prisma client is generated, the generator parses its output files (index.d.ts for prisma-client-js, .ts files for prisma-client) into an abstract syntax tree (AST) with oxc-parser.

For each model property in the AST, it looks up the field's type comment in the DMMF. When there is one, the generator replaces the source text of the original type node (such as Prisma.JsonValue or string) with your type. See the core implementation for details.

Limitations

  • JsonFilter and JsonWithAggregatesFilter stay untyped so that filtering keeps working.
  • prisma-json-types-generator@6 only supports Prisma 7.10 or later.
  • If a Json field is not typed correctly, please open an issue.

Legacy versions

Since v6, the generator parses Prisma's output with oxc-parser instead of the TypeScript compiler, so it works with the TypeScript version your project already uses. The generated types are tested with TypeScript 5.9 and 7.

| Version | Prisma | TypeScript | | ---------------- | ------- | ----------------------------------- | | 6.x | 7.10+ | Not used by the generator | | 5.1.1 to 5.x | 7.8+ | Bundles its own TypeScript 6 | | 5.0 to 5.1.0 | 7.8+ | TypeScript 6 as a peer dependency | | 4.x | 7 | TypeScript 5.9 as a peer dependency | | 3.x | 5 and 6 | TypeScript 5 as a peer dependency |

License

Licensed under the MIT license. See LICENSE.