简体   繁体   English

在Typescript中强制转换功能参数对象属性

[英]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? 有什么方法可以强制转换第二个参数的payload属性? 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: 我知道可以通过命名对象并将其强制转换为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. 在这种情况下,我会得到预期的输入,但是我希望有一个捷径,因为我有很多这样的功能,我宁愿不必创建一堆接口就可以在一个实例中使用它们这个。

You can type destructed parameter inline: 您可以内联键入破坏参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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