【问题标题】:How to define generic response type over exitants API using typescript如何使用打字稿在exitants API上定义通用响应类型
【发布时间】:2021-05-03 14:36:36
【问题描述】:

我在尝试定义继承模型以便从我的 API 做出通用响应时遇到问题。

关键是我所有的响应当前都有一个状态和一个状态消息加上响应的内容在同一级别进入对象。

所以 resp1 结构很容易定义为 ResponseBaseContentOf,但是如何使用 ResponseBaseInheritsOf 之类的东西来定义 resp2 响应样式?你能看出区别吗?

export type ResponseStatus = 'OK' | 'NOK'
export const ResponseStatus = {
    Ok: 'OK' as ResponseStatus,
    Nok: 'NOK' as ResponseStatus
}

export interface ResponseBase {
    status: ResponseStatus,
    message: string
}

export interface ResponseBaseContentOf<T> extends ResponseBase {
    content: T
}

export interface MyClass {
    property01: string
    property02: number
}

const resp1: ResponseBaseContentOf<MyClass> = {
    status: 'OK',
    message: 'response ok',
    content: {
        property01: '01',
        property02: 2,
    }
}


ResponseBaseInheritsOf<MyClass>

const resp2 = {
    status: 'OK',
    message: 'response ok',
    property01: '01',
    property02: 2
}

【问题讨论】:

  • 请提供 NOK 回复

标签: typescript api inheritance response


【解决方案1】:

为了输入失败/成功的行为,我相信你应该使用代数数据类型。

您有两个有效状态:SuccessFailure。 (在您的特定情况下OK和NOK)

因此,我假设您在响应中的数据也应该有两种状态。

const enum Messages {
  Success = 'Success',
  Failure = 'Failure'
}

type Success = {
  status: Messages.Success,
  message: string
}

type Failure = {
  status: Messages.Failure,
  message: null
}

type MyResponse = Success | Failure;

现在,您只有两种可能的状态。

正如你可能已经注意到的,你不能那样做:

const response: MyResponse = {
  status: Messages.Success,
  message: null
} // error, message should be string


const response2: MyResponse = {
  status: Messages.Success,
  message: 'some message'
} // ok

您需要做的就是让非法状态无法再现。

为了做到这一点 - 你可以使用 TypeScript union - 我相信这是最常见的方法。

由于您没有在成功的情况下提供有关数据结构的任何信息,因此我无法帮助您在特定情况下定义您的类型。

请提供成功和失败响应之间的一些区别 - 然后我会更新我的答案。

现在,希望对你有帮助

更新

我认为你正在寻找这样的东西:

export type ResponseStatus = 'OK' | 'NOK'
export const ResponseStatus = {
    Ok: 'OK' as ResponseStatus,
    Nok: 'NOK' as ResponseStatus
}

export interface ResponseBase {
    status: ResponseStatus,
    message: string
}

type ResponseBaseContentOf<T> = ResponseBase & T

export interface MyClass {
    property01: string
    property02: number
}

const resp1: ResponseBaseContentOf<MyClass> = {
    status: 'OK',
    message: 'response ok',
    property01: '01',
    property02: 2,
}

顺便说一句,here 你可以找到一些输入 api 请求的替代方法,here 你可以找到更多关于联合的信息

【讨论】:

  • 你是对的!我已经编辑了解释,示例显示了 OK 响应......我认为联合也是正确的方法,但我没有得到用于编写 ResponseBaseInheritsOf 规范的符号,使用泛型或其他东西,为了表示 resp2
  • 我更新了。尝试使用交集以摆脱 content 属性
  • 十字路口!就是这样!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
相关资源
最近更新 更多