You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript如何传递复杂类型变量给函数而无需重定义类型

解决Prisma查询类型复用的常用方法

不用手动重写复杂类型,这两个方法直接复用Prisma生成的类型:

方法一:用typeof直接提取变量类型

这是最快捷的方式,直接从已查询的users变量里提取单个用户的类型:

const users = await prisma.user.findMany({
    select:{
        projects: {
            select: {
                name: true,
                slug: true,
                _count:{
                    select: {
                        subscribers: true,
                        mediaIds: true
                    }
                }
            },
        },
        id: true,
        email: true,
        firstName: true,
        lastName: true,
        createdAt: true,
        _count:{
            select:{
                mediaIds: true,
                projects: true
            }
        }
    },
});

// 提取单个用户的类型,加NonNullable避免undefined(如果findMany可能返回空数组的话)
type UserWithProjects = NonNullable<typeof users[0]>;

users.forEach(user=>{
  handleUser(user)
});

function handleUser(user: UserWithProjects){
  // 这里自动获得完整的类型提示,比如user.projects、user._count都能正常提示
}

方法二:用Prisma官方的GetPayload提前定义类型

如果需要在查询前就定义好类型(比如跨文件复用),可以用Prisma自带的UserGetPayload工具类型,先把查询的select逻辑抽出来复用:

import { Prisma } from '@prisma/client';

// 先把select配置抽成变量,用satisfies确保符合Prisma的类型规范
const userSelectConfig = {
    projects: {
        select: {
            name: true,
            slug: true,
            _count:{
                select: {
                    subscribers: true,
                    mediaIds: true
                }
            }
        },
    },
    id: true,
    email: true,
    firstName: true,
    lastName: true,
    createdAt: true,
    _count:{
        select:{
            mediaIds: true,
            projects: true
        }
    }
} satisfies Prisma.UserSelect;

// 用GetPayload生成对应的类型
type UserWithProjects = Prisma.UserGetPayload<{ select: typeof userSelectConfig }>;

// 查询时直接复用这个配置
const users = await prisma.user.findMany({ select: userSelectConfig });

function handleUser(user: UserWithProjects){
  // 同样能获得完整类型提示
}

这两种方法都不用手动写那些冗长的嵌套类型,完全复用Prisma自动生成的类型信息,既省心又不会出错。

内容的提问来源于stack exchange,提问作者Bengin Cetindere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:40:11