[英]Pick from return type by using function parameters
我正在使用 Graphql 和 Typescript,我想告诉我的函数我想从请求中返回什么数据,并让 Typescript 知道这些类型是什么。
这是我的代码:
// This was auto-generated by my schema builder, I cannot modify it or change its shape
type User = {
id: string;
name: string | null;
email: string | null;
emailVerified: Date | null;
image: string | null;
role: Role;
}
export const getUsers= (
params: (keyof User)[]
): Pick<User, typeof params[0]>[] => {
// graphql request here
}
这编译并允许我只传递存在于User
类型中的参数,但是我似乎无法让 Typescript 只Pick
我作为参数传递的类型。
例如:
const users = getUsers(['id']);
// This won't error
console.log(users.name)
我认为这是因为我在做typeof params[0]
,所以它只是检查类型而不是作为参数传递的字符串。
这甚至可以使用 Typescript 吗?
您需要向函数添加泛型类型:
export const getUsers = <K extends (keyof User)[]>(
params: [...K]
): Pick<User, K[number]>[] => {
return {} as any
}
K
将保存您传递给函数的元组的类型信息。 通过使用K[number]
,我们得到了元组中所有元素的并集,我们可以将其用于Pick
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.