I'm currently delving into the world of Graphql and Typescript, trying to specify the data I want returned from a request and communicate those types effectively in my functions.
Below is the snippet of code that showcases my current approach:
// The following structure was auto-generated by the schema builder and cannot be altered
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 API call here
}
This setup enables me to specifically choose parameters based on the properties present in the User
type. Nevertheless, I've encountered an issue where I struggle to instruct Typescript to pick only the specified types passed as arguments.
For instance:
const users = getUsers(['id']);
// This does not raise any error
console.log(users.name)
My assumption is that this inconsistency stems from utilizing typeof params[0]
, which essentially checks the type rather than validating the actual strings supplied as parameters.
Do you think it's achievable with Typescript?