简体   繁体   中英

How to ensure JSON object structure using type and interface in Angular?

I have a couple of modules and components in my angular project. I have created a router config file for easy handling of routing and it contains JSON data as follows.

router.config.ts

 {
   branch:{
     list:'/app/branch/list',
     add:'/app/branch/add'
   },
   books:{
      publish:'/app/books/publish',
      manage:'/app/books/manage'
   }
 }

So based on configuration, the routing would be easy.

<a routerLink="branch.list">
  Branch list
</a>

<a routerLink="books.publish">
  Publish book
</a>

I want to validate the router config objects. How do I validate that by using interface and type ?

interface Route {
    [key: string]:
    { [key: string]: string }
}

const Routes :Route[] = [
{
    branch:{
      list:'/app/branch/list',
      add:'/app/branch/add'
    },
    books:{
       publish:'/app/books/publish',
       manage:'/app/books/manage'
    }
  }
];

define router Item like this:

interface RouterItem {
  list: string;
  add: string;
}

and this function for instance validation:

function isInstanceOfRouterItem(obj: any){
  return 'list' in obj && 'add' in obj;
}

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