如何将 TypeScript 接口添加到 shorthand 变量?

How to add TypeScript Interface to shorthand variable?

如何将 TypeScript 接口设置为如下所示的变量:

const { body, statusCode } = await got.post('smth', requestOpts)

如何将界面设置为ex。 body。我想在那里分配一个接口,其中包含来自服务器的潜在请求。我愿意实现的接口如下所示:

    interface ResponseBody {
        data: [{ username: string }]
    }

我尝试了不同的方法来将此接口附加到上层变量 body 但我遇到了构建错误。我在这里唯一的解决方法是不使用 shorthand 变量,但这不是我的目标 - 我想知道是否有针对此类问题的解决方案。

TypeScript Playground

您需要 annotate 整个对象,如下所示:

const { body, statusCode }: { body: ResponseBody, statusCode: number } =
    await got.post<ResponseBody>('users', requestOpts)

虽然如果您能对个人进行注释就更好了 destructured variables inside the object, this is not currently possible. The syntax const { body: ResponseBody } = ... can't work because JavaScript interprets this as assigning to a new variable name (so there'd be a variable named ResponseBody holding the value that was in the body property). Perhaps something like const { body::ResponseBody, statusCode::number } would work instead, as requested in microsoft/TypeScript#29526。但目前这是不可能的,你必须对整个对象进行注释。


这就是问题的答案。

请注意,对于您的特定示例,got.post() method has a call signature that's generic 是您期望 body 属性 的类型。所以你可以写

const { body, statusCode } = await got.post<ResponseBody>('users', requestOpts);

以最少的额外击键获得强类型 body 变量。

Playground link to code