Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pick from return type by using function parameters

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading