繁体   English   中英

Typescript:如何在不重新定义类型的情况下将复杂类型的变量传递给 function

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

我对 typescript 有点陌生,我现在有几次。 我使用例如棱镜(或任何东西)来获取一个类型非常复杂的值(如长)。

它有很多属性,而且非常好。 一旦我想定义一个 function 来处理这个值,我就会丢失所有类型信息,因为我必须在参数中重新定义这个复杂类型。

例子:

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

现在我想定义一个 function 来例如处理其中一个订阅者:

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
}

我很困惑这里的常用方法是什么。

您可以使用定义User model 的 class。 您在 orm 文件中定义一次 model,然后您可以使用User类型来键入您的参数。 Typescript 无法知道参数用户是用户,因此您必须输入

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

要在 TypeScript 中定义大类型,请对对象使用interface ,或为微小细节使用type

例子:

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

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

在此示例中,如果您有一个定义 Human 的 class,请将其用作类型。

如果users数组在 function 的 scope 中可用,则可以使用typeof运算符。

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

您可以使用number索引typeof users的类型以获取users内部数组元素的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM