Working with TypeScript Types
1. Using Generated Model Types
import type { User, Post } from "@prisma/client";
function greet(u: User) { return `Hi, ${u.name ?? "friend"}`; }
| Type | Detail |
| User | All scalar fields of the model |
| Relations | Not included by default |
2. Creating Custom Payload Types
import type { Prisma } from "@prisma/client";
type UserWithPosts = Prisma.UserGetPayload<{ include: { posts: true } }>;
| Helper | Use |
Prisma.<Model>GetPayload<T> | Compute query result type |
| Validator | Prisma.validator<Prisma.UserDefaultArgs>()(args) |
3. Using Type Helpers
| Type | Use |
Prisma.UserCreateInput | Shape for create |
Prisma.UserUpdateInput | Shape for update |
Prisma.UserWhereInput | Shape for filters |
Prisma.UserSelect | Allowed select keys |
4. Implementing Type Guards
function isAdmin(u: User): u is User & { role: "ADMIN" } {
return u.role === "ADMIN";
}
| Pattern | Use |
| Predicate | Narrow union types |
| Discriminator | Combine with literal types |
5. Using Partial Types
| Helper | Use |
Partial<User> | All fields optional |
Pick<User, "id" | "email"> | Subset |
Omit<User, "password"> | Exclude fields |
6. Creating Union Types
type Identifier = { id: number } | { email: string };
| Use | Detail |
| Polymorphic IDs | findBy either id or email |
| Result variants | { kind: "ok" } | { kind: "err" } |
7. Using Utility Types
| Utility | Detail |
Required<T> | All fields required |
Readonly<T> | Immutable |
Awaited<T> | Resolve Promise type |
8. Typing Raw Query Results
| API | Detail |
$queryRaw<T> | Generic return type |
Prisma.sql | Safe composition |
9. Implementing Generic Functions
async function findById<K extends keyof typeof prisma>(
model: K, id: number
) {
return (prisma[model] as any).findUnique({ where: { id } });
}
| Trade-off | Detail |
| Reusability | One helper for all models |
| Type safety | Loses inference; consider per-model |
10. Configuring Strict Null Checks
{ "compilerOptions": { "strict": true, "strictNullChecks": true } }
| Setting | Effect |
| strict | Enables all strict checks |
| strictNullChecks | Treat null/undefined distinctly |