【问题标题】:typescript - cast json to an interfacetypescript - 将 json 转换为接口
【发布时间】:2018-10-27 16:51:45
【问题描述】:

我有一个这样的界面:

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

当我从服务器获取数据时,json 文件包含更多这样的属性:

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

但我只需要 id、name 和 description 字段。我试过这个:

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

但对象包含不必要的数据,如 url、startdate 和 finishDate 我怎样才能正确映射它们? 我知道我们可以像这样映射它们:

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

但是还有其他更好的方法吗?

【问题讨论】:

标签: json typescript interface


【解决方案1】:

我建议你做你正在做的事情,但另外为你的服务器响应添加一些类型。这样你就可以为你的映射函数获得一些智能感知。

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);

【讨论】:

    猜你喜欢
    • 2017-04-25
    • 2016-09-09
    • 2018-05-05
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 2018-11-28
    相关资源
    最近更新 更多