简体   繁体   English

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

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

I have an interface like this: 我有一个像这样的界面:

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
    }[]
}

now I have a function return Response : 现在我有一个函数返回Response

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

However, data.htw.cart.list return APIResponse , I just need Response , I get too much data. 但是, data.htw.cart.list返回APIResponse ,我只需要Response ,我得到了太多数据。

every time I need to do this: 每次我需要这样做时:

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

I want to have a tool to remove some data in APIResponse which make APIResponse becomes Response ? 我想要一个工具来删除APIResponse中的一些数据,这些数据会使APIResponse成为Response

Two things to point out: 有两点要指出:

  1. APIResponse always include Response APIResponse始终包含Response
  2. key name in Response which includes is the same as in APIResponse Response中的键名与APIResponse键名相同

I think the cleanest way would be to create the appropriate relations between your types. 我认为最干净的方法是在您的类型之间创建适当的关系。

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;

So this helps to make the compiler understand how your types are related to each other. 因此,这有助于使编译器了解您的类型如何相互关联。

If you want to "physically" remove the excess fields, then the best you can do is the .map what you posted in your question. 如果您想“物理上”删除多余的字段,那么最好的办法就是在问题中张贴的.map You can also use a js library (eg.: lodash/pluck ) - but then you defeat the purpose of having statically checked types... 您还可以使用js库(例如: lodash / pluck )-但随后您就无法实现静态检查类型的目的...

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

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