Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
Ramin Ahmadi Avatar asked Aug 17 '26 12:08

Ramin Ahmadi


1 Answers

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);
like image 190
jcreamer898 Avatar answered Aug 19 '26 04:08

jcreamer898



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!