typescript泛型约束的问题?

ts初学者?
这个该怎么改
image.png

  interface MetaObj {
    displayName: string
    path: string
    active: string | null
    headActive?: string
  }
  
  type route = {
    path: string,
    index: string,
    redirect: string | null,
    name: string,
    meta: MetaObj,
    icon: string,
    iconName: string,
    children: route[] | null,
  }
  
  class RouteDo<T extends route> {
    constructor(private routes: T[]){}
    public formatRoutes(routes: T[] = this.routes, parentNode?: T): T[]{
      routes.forEach((item: T) => {
        if(parentNode){
          item.meta.headActive = parentNode.meta.headActive
        } else {
          item.meta.headActive = item.index
        }
        if(item.children && item.children.length) {
          item.children = this.formatRoutes(item.children, item)
        }
      })
      return routes
    }
  }
阅读 1.9k
1 个回答

另定义一个接口描述描述它的chilren属性为当前类的数组
route再通过泛型的方式定义它的children属性

interface MetaObj {
  displayName: string
  path: string
  active: string | null
  headActive?: string
}

interface RouteItem {
  path: string
  index: string
  redirect: string | null
  name: string
  meta: MetaObj
  icon: string
  iconName: string
  children: RouteItem[] | null
}

type route<T> = {
  path: string,
  index: string,
  redirect: string | null,
  name: string,
  meta: MetaObj,
  icon: string,
  iconName: string,
  children: T[] | null,
}


class RouteDo<T extends route<T>> {
  constructor(private routes: T[]){}
  public formatRoutes(routes: T[] = this.routes, parentNode?: T): T[]{
    routes.forEach((item: T) => {
      if(parentNode){
        item.meta.headActive = parentNode.meta.headActive
      } else {
        item.meta.headActive = item.index
      }
      if(item.children && item.children.length) {
        item.children = this.formatRoutes(item.children, item)
      }
    })
    return routes
  }
}

var routes: route<RouteItem>[] = []


const r: RouteDo<RouteItem> = new RouteDo(routes)
const result = r.formatRoutes()
console.log(result)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题