简体   繁体   中英

Typing for graphql resolver function

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM