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

Time:08-07

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.

CodePudding user response:

You can use the class that define the User model. You define the model one time in the orm file and then you can use the User type to type your parameters. Typescript cannot know that the param user is an user so you have to type it

function handleUser(user: User){
  // handle the user
}

CodePudding user response:

To define a large type in TypeScript, use interface for objects, or type for tiny details.

Example:

interface HumanType {
  name: string;
  age: number;
}

const human: HumanType = { name: "Thomas", age: 34588 }

In this example, if you have a class that defines a Human, use it as a type.

  • Related