Search code examples
javascripttypescriptprisma

Typescript: how to pass variable with complex type to a function without redefining type


I am kind of new to typescript and I had this a few times now. I use for example prisma (or anything) to get a value which's type is monstrously complex (as in long).

It has many attributes and those are perfectly fine. As soon as I want to define a function to handle this value, I lose all the type information since I'd have to redefine this complex type in the parameter.

Example:

    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
                }
            }
        },
    });

And now I want to define a function to for example handle one single of those subscribers:

users.forEach(user=>{
  // here I have perfect typing for the user object
  handleUser(user)
});
function handleUser(user: <what to put here?>){
  // here I'd have to retype / redefine the monstreously long (but helpful) dynamic type that prisma creates for my query
}

I am confused what the common approach is here.


Solution

  • If the users array is avaiable in the scope of the function, you could use the typeof operator.

    function handleUser(user: typeof users[number]){
      
    }
    

    You can index the typeof users with number to get the type of an array element inside users.