3

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?

1

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.