Artem Zakharov
Artem Zakharov

Reputation: 845

Casting a function parameter object property in Typescript

I have a function that looks like this:

getShopItems: async (parent, { payload }, ctx: Context, info) => { ... }

Is there any way to cast the payload property of the second argument? I'd like to do something like this, for example:

getShopItems: async (parent, { payload: ItemSearchPayload }, ctx: Context, info) => { ... }

I'm aware that I can fix this issue by naming the object and casting it to something, a la:

interface Args {
  payload: ItemSearchPayload;
}

getShopItems: async (parent, args: Args, ctx: Context, info) => { ... }

and in this case I would get typings as expected, but I'm hoping that there's a shortcut because I have a lot of functions like this and I would prefer not to have to create a bunch of interfaces just to use them in one instance like this.

Upvotes: 0

Views: 2230

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 38046

You can type destructed parameter inline:

getShopItems: async (
    parent,
    { payload }: { payload: ItemSearchPayload },
    ctx: Context, info
) => {
    // ...
}

Upvotes: 1

Related Questions