简体   繁体   中英

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:

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

but I only need the id, name and description fields. 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? 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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