打字稿定义 POST 请求响应的类型

Typescript define the type of a POST request response

我有一个 post 请求,使用的是这样的:

const got = got_.extend({
  prefixUrl: serviceUrl,
  responseType: 'json'
})

const { body } = await got.post('newAddress', {
  json: {
    userId
  }
})

Body 总是要么是一个对象,要么具有 属性“newAddress”,要么具有属性“errorCode”和“newAddress”。如果它是 newAddress,它只是一个字符串。如果它是错误的,它是一个带有错误代码和错误消息的对象

type ResponseError = {
  error: {
    errorCode: string
    message: string
  }
  newAddress?: never
}

type AddressResponse = {
  newAddress: string
  error?: never
}

type NewAddressResponse = AddressResponse | ResponseError

这就是我目前使用 body 常量的方式:

if (body.error) throw new Error(JSON.stringify(body.error))
    return res.json({ newAddress: body.newAddress })

使用我的类型 NewAddressResponse 的正确方法是什么?

目前我试过这个: const { body }: { body: NewAddressResponse } = await got.post ...

但是我有错误:

Type 'Response<string>' is not assignable to type '{ body: NewAddressResponse; }'.
  Types of property 'body' are incompatible.
    Type 'string' is not assignable to type 'NewAddressResponse'.

上面说 got.post returns 类型 CancelableRequest<Response<string>> 但我已经将响应类型设置为 'json'。

如何正确地为这个 got.post 的响应分配类型?

got 支持泛型类型,因此您可以将类型 - NewAddressResponse 传递给 post() 以进行推断

const { body } = await got.post<NewAddressResponse>('newAddress', {
  json: {
    userId
  }
})