40

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)

2 Answers 2

65

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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!
Count me in the "unacceptable" camp. Looks like it's being worked on but taking a long time - github.com/Microsoft/TypeScript/issues/29526
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)
7

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.