繁体   English   中英

Angular中使用类型和接口如何保证JSON object结构?

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

我的 angular 项目中有几个模块和组件。 我创建了一个路由器配置文件,以便于处理路由,它包含 JSON 数据,如下所示。

路由器.config.ts

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

因此,基于配置,路由将很容易。

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

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

我想验证路由器配置对象。 如何通过使用interfacetype来验证这一点?

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'
    }
  }
];

像这样定义路由器项目:

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

这个 function 用于实例验证:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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