繁体   English   中英

如何根据Typescript中的接口新建对象?

[英]How to new an Object according to interface in Typescript?

我有一个像这样的界面:

interface Response {
    items: {
        productId: string;
        productName: string;
        price: number;
    }[]
}

interface APIResponse {
    items: {
        productId: string;
        productName: string;
        price: number;
        factoryId: string,
        status: number,
        category: number,
        priority: number
    }[]
}

现在我有一个函数返回Response

async function list(): promise<Response> {
    // data.htw.cart.list return APIResponse
    const rv = await data.htw.cart.list(postJson)
    return rv
}

但是, data.htw.cart.list返回APIResponse ,我只需要Response ,我得到了太多数据。

每次我需要这样做时:

return {
  items: rv.items.map(item => {
    return {
      productId: item.productId,
      productName: item.productName,
      price: item.price
    }
  })
}

我想要一个工具来删除APIResponse中的一些数据,这些数据会使APIResponse成为Response

有两点要指出:

  1. APIResponse始终包含Response
  2. Response中的键名与APIResponse键名相同

我认为最干净的方法是在您的类型之间创建适当的关系。

interface Item {
  productId: string
  productName: string
  price: number
}

interface APIItem extends Item {
  factoryId: string,
  status: number,
  category: number,
  priority: number
}

interface Response {
  items: Item[]
}

interface APIResponse extends Response {
  items: APIItem[]
}

// APIResponse is now assignable to Response
let response: Response = ...;
let apiResponse: APIResponse = ...;
response = apiResponse;

// APIItem[] is now also assignable to Item[], but you only loose 
// the type information, the fields will be there actually
const apiItems: APIItem[] = [...];
const items: Item[] = apiItems;

因此,这有助于使编译器了解您的类型如何相互关联。

如果您想“物理上”删除多余的字段,那么最好的办法就是在问题中张贴的.map 您还可以使用js库(例如: lodash / pluck )-但随后您就无法实现静态检查类型的目的...

暂无
暂无

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

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