0
votes

Looked at examples on how to write type for currying functions, but I still can’t connect the two.

This is the function I have for my resolver

export default {
  Query: { 
    Name: getResolver(‘name’, ‘special’)
  }
}

function getResolver(n: string, type: string) {
   return (parent, args, ctx) => { ... }
}

I try to do this but it does not work.

type GetResolver = <t, t1, t2>() => (parent: t...) => ... 

and

type NameResolver = (t, t1, t2)=> ...
type GetResolver = (...) => NameResolver

I know those types are wrong, but I am not sure what is missing here.

How do we write type for graphql resolver functions?

1
I edit your code to adopt more meaningful variable names. Now you need to tell us more about params of getNameResolver(n, type), n and type what do they stand for? More context is needed to answer your question. - hackape
n and type are keys we use to locate specific data. for example loader[type][n] to retrieve a value, and for each of the type, it returns a different type. for example special expects to return string, while junk to return number - roger

1 Answers

2
votes

Work in progress. Waiting for response from OP.

Check below, I still don't get the whole picture, need more input. Nonetheless I put together this piece of code base on your comment.

interface NameParent {}
interface NameArgs {}

const resolvers = {
  name: {
    special: function (parent: NameParent, args: NameArgs, ctx: any) {
      return 'string'
    },
    junk: function (parent: NameParent, args: NameArgs, ctx: any) {
      return 1
    }
  }
}

type ResolverType = keyof typeof resolvers

function getResolver<T extends ResolverType, K extends 'special' | 'junk'>(type: T, key: K) {
  return resolvers[type][key]
}

const specialNameResolver = getResolver('name', 'special')
// const specialNameResolver: (parent: NameParent, args: NameArgs, ctx: any) => string

const junkNameResolver = getResolver('name', 'junk')
// const junkNameResolver: (parent: NameParent, args: NameArgs, ctx: any) => number