Home > OS >  Pick from return type by using function parameters
Pick from return type by using function parameters

Time:06-24

I'm working with Graphql and Typescript and I'd like to tell my functions what data I want returned from a request and for Typescript to know what those types are.

This is my code:


// 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
}

This compiles and allows me to only pass parameters that exist in the User type, however I can't seem to get Typescript to Pick just the types I've passed as arguments.

For example:

const users = getUsers(['id']);

// This won't error
console.log(users.name)

I assume this is because I'm doing typeof params[0], so it's just checking the type and not the strings that are passed as parameters.

Is this even possible with Typescript?

CodePudding user response:

You need to add a generic type to the function:

export const getUsers = <K extends (keyof User)[]>(
  params: [...K]
): Pick<User, K[number]>[] => {
  return {} as any
}

K will hold the type information of the tuple you pass to the function. By using K[number] we get a union of all elements in the tuple which we can use for Pick.

Playground

  • Related