0

I am defined the MenuItem like this to parse the server side rest api response:

  type MenuItem = {
    id: number;
    name: string;
    path: string;
    tree_id_path: string;
    children: MenuItem[];
  };

the server side return more than 4 fields, but I only want the MenuItem to take 4 fields. what should I do to make it work like this? Now I am using as to cast the reponse to MenuItem list.

  export async function roleMenuTree(options?: { [key: string]: any }) {
    let response = await request<API.ApiResponse>('/manage/permission/role/v1/role/menu', {
      method: 'POST',
      body: JSON.stringify({}),
      ...(options || {}),
    });
    let dataList = response.result as API.MenuItem[];
    return dataList;
  }
Dolphin
  • 29,069
  • 61
  • 260
  • 539
  • Do you need to actually remove the extra properties from the object? Or just have typescript assume the properties don't exist and thus give you an error if you try to access them? – Nicholas Tower Apr 23 '22 at 10:00
  • Does this answer your question? [Is it possible to restrict TypeScript object to contain only properties defined by its class?](https://stackoverflow.com/questions/49580725/is-it-possible-to-restrict-typescript-object-to-contain-only-properties-defined) – pilchard Apr 23 '22 at 10:01
  • also: [TypeScript : avoid extra properties](https://stackoverflow.com/questions/61960321/typescript-avoid-extra-properties) – pilchard Apr 23 '22 at 10:02

2 Answers2

1

You can easily achieve this using es6.

By using the Spread syntax

let { unWantedFields ,...rest} = response.result;
let result = rest

Or you can use Destructuring assignment to include your desire props

let {id, name, path} = response.result;
let result = {id, name, path}
Yedidya Rashi
  • 1,012
  • 8
  • 18
1

As an alternative you can return a new object

export async function roleMenuTree(options?: { [key: string]: any }) {
    let response = await request<API.ApiResponse>('/manage/permission/role/v1/role/menu', {
      method: 'POST',
      body: JSON.stringify({}),
      ...(options || {}),
    });
    let newResult: MenuItem = {
      id: response?.result?.id,
      name: response?.result?.name,
      path: response?.result?.path,
      tree_id_path: response?.result?.tree_id_path,
      children: //Here your MenuItem[]
    }
    let dataList = newResult;
    return dataList;
  }

Or you can use this approach (If you have same names in api response as well)

   let {id, name, path, tree_id_path, children} = response.result;
Evren
  • 4,147
  • 1
  • 9
  • 16