简体   繁体   English

打字稿-将json转换为接口

[英]typescript - cast json to an interface

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

export default interface IProject extends{
    Id?:number;
    name?:string;
    description?:string;
}

and I when get data from the server the json file includes more properties like this: 当我从服务器获取数据时,我的json文件包含更多类似的属性:

{
    id,
    name,
    description,
    url,
    startDate,
    finishDate
}

but I only need the id, name and description fields. 但我只需要ID,名称和说明字段。 I tried this: 我尝试了这个:

response.data.map((p: any) => p as IProject);

but the object includes the unnecessary data like url, startdate and finishDate how can I map them correctly? 但是对象包含不必要的数据,例如url,startdate和finishDate,如何正确映射它们? I know that we can map them like this: 我知道我们可以这样映射它们:

response.data.map((p: any) => {
    return {id:p.id,name:p.name,description:p.description}
});

but is there any other better ways to do that? 但是还有其他更好的方法吗?

I'd recommend doing what you're doing, but additionally adding some types for your server response as well. 我建议您做您正在做的事情,但同时还要为服务器响应添加一些类型。 That way you get some intellisense for your mapping functions. 这样,您将获得一些映射功能的智能感知。

interface IProject {
  id?: number;
  name?: string;
  description?: string;
}

interface IProjectResponse {
  id?: number;
  name?: string;
  description?: string;
  url?: string;
  startDate?: string;
  finishDate?: string;
}

const mapResponse = (response: IProjectResponse[]) => response.data.map((p) => ({
  id: p.id,
  name:p.name,
  description: p.description,
}));

const response = await fetch(/* .. */);
const data = await response.json();

const projects: IProject[] = mapResponse(data);

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

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