当我的API响应类型定义为接口时如何添加功能?

问题描述 投票:0回答:1

我有一个 React 应用程序,为了使重构更容易,我需要在我的 Product 类型上添加一个扩展方法:

product.hasAbc() // boolean check that references the attributes property
product.hasDef() // boolean check

目前我的 API 返回一个响应,然后该响应绑定到打字稿接口类型。

下面是我的产品

Interface
,然后是解码 API json 响应的
decoder
。我实际的 axios 函数使用的是产品解码器。

export interface Product {
  readonly id: string;
  readonly attributes: ReadOnlyArray<string>,
  ...
}

export const productDecoder = JsonDecoder.object<Product>(
  {
    id: JsonDecoder.string,
    ...
  },
  "Product"
);

async function decodeResponse<T>(decoder: JsonDecoder.Decoder<T>, responseData: any): Promise<T> {
  return decoder.decodePromise(responseData);
}



export async function getProduct(): Promise<Product> {
  return new Promise((resolve, reject) => {
    customAxios.get("/api/products/123")
      .then(response =>
        decodeResponse<Product>(productDecoder, response.data).then(resolve).catch(reject)
      )
      .catch(error => reject(pathOr("Error...", errorMsgPath, error)));
  });
}

如何在属性上添加扩展方法,以便我可以做到:

const hasAbc = () => {
   this.attributes.contains("abc")
}

参考:该项目使用ts.data,这是一个解码库:https://github.com/joanllenas/ts.data.json

javascript reactjs typescript
1个回答
0
投票

您可以在

Array
对象的原型上定义一个新方法。例如:

Array.prototype.IsTrue = function () {
    return true;
}

然后使用它:

product.attributes.IsTrue()

但是这个方法将存在于 Array 对象的每个实例上。例如:

[1,'abc'].IsTrue()
是有效用法。

你不能只为你选择的一个接口定义扩展方法,因为javascript实际上没有

Interface
Type
的概念。这只是 Typescript 带来的一项语言功能,旨在帮助您的开发人员生活更轻松。

© www.soinside.com 2019 - 2024. All rights reserved.