Using this package? Please consider donating to support my open source work ❤️
If this project helps you, star the repository and share it with your co-workers.
[!IMPORTANT]
prisma-json-types-generator@6supports 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
Jsonand scalar fields of the Prisma client.
String fields (enums)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.
Json fields, including Json[] lists.String, Int and Float fields, which gives you enums without native database enums.@prisma/client generators at once, useful while moving the client to a new output location.npm install -D prisma-json-types-generator
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.
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" |
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"
}
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;
};
}
}
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'
}
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'.
A field can reference a type from the namespace or have its type written inline:
/// [TypeName] references a type in the PrismaJson namespace. Use it for complex or reused types./// ![Type] takes a TypeScript type written in the schema. Use it for small one-off types such as unions or simple objects.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:
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.String, Int and Float fields, nullable ones included.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.
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:
pg. You already have it if you use @prisma/adapter-pg.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.
.sql fileComputed 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.
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.
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:
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.
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.
JsonFilter and JsonWithAggregatesFilter stay untyped so that filtering keeps working.prisma-json-types-generator@6 only supports Prisma 7.10 or later.Json field is not typed correctly, please open an issue.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 |
Licensed under the MIT license. See LICENSE.