35

I'm trying to give a type to the members of below function. args is an object with a data property of type UserCreateInput

So, from this:

createUser(parent: any, args: any, context: any) {
    return context.prisma.createUser(args.data)
}

I wrote this:

createUser(parent: any, args: {data: UserCreateInput}, context: any) {
    return context.prisma.createUser(args.data)
}

I'm not sure how to replace 'xxx' in createUser(parent: any, xxx, context: any) so I can simply return return context.prisma.createUser(data)

Greg Forel
  • 2,199
  • 6
  • 25
  • 46

2 Answers2

57

You can use the object de-structuring syntax:

createUser(parent: any, { data }: { data: UserCreateInput }, context: any) {
    return context.prisma.createUser(data)
}

Unfortunately it is required you write data twice. There is a proposal to fix this but there are issues around this.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • Thanks! I don't mind using data twice. I read about object destructuring, but clearly I need to read again... – Greg Forel Feb 04 '19 at 09:52
  • 50
    I think it's terrible. I use parameter destructuring all the time in Javascript, and now everything has to be duplicated and everybody thinks it's normal? No language I've hrydseen does that! Seriously, look at how ugly that thing gets! – html_programmer Oct 10 '20 at 23:57
  • 6
    Count me in the "unacceptable" camp. Looks like it's being worked on but taking a long time - https://github.com/Microsoft/TypeScript/issues/29526 – Vasek Tobey Vlcek Jan 25 '22 at 08:22
  • I have concluded typescript's maintainers have gone crazy the moment they started backing the solution to importing ES modules named `./local/module.ts` with the js file extension `./local/module.js` (even though the filename is `./local/module.ts`) – Bersan Aug 03 '23 at 21:27
3

A widely used and arguably less ugly alternative to inline object types is to define the destructured object as a named args or props type. For example:

interface CreateUserArgs {
  data: UserCreateInput
}

createUser(parent: any, { data }: CreateUserArgs, context: any) {
    return context.prisma.createUser(data)
}

Sadly it still requires duplicating the property names (and means you need to give it a name), but it has two potential benefits:

  • It doesn't fill the arguments list with brackets, so it's easier to see what the top-level arguments are and how many there are
  • The type can be exported and used in other files (e.g. by consumers of this function if building the object of args is not just inline when the function is called
user56reinstatemonica8
  • 32,576
  • 21
  • 101
  • 125