Search code examples
typescriptvue.jsvue-router

How do you type vue-router meta attribute to be required?


I have typed the vue-router meta fields according to the manual, for example:

declare module 'vue-router' {
  interface RouteMeta {
    // must be declared by every route
    requiresAuth: boolean
  }
}

These meta fields must be configured by the developer. Making it non-null ensures that typescript throws an error if meta is defined but requiresAuth isn't. However, it does not check if meta is defined and if it isn't, there are no errors.

How do I make sure that meta is defined for every route?


Solution

  • It's not a good practice to modify global behaviour for local purposes. Routes array can have custom type that fits the expectations. E.g. for routes with mandatory name and meta it's something like:

    interface RouteCommonMeta {
      ...
    }
    
    interface RouteCommonDef {
      name: RouteRecordName;
      meta: IRouteCommonMeta;
      children?: RouteDef[];
    }
    
    export type RouteDef = RouteRecordRaw & RouteCommonDefinition;
    
    
    const routes: RouteDef[] = [...];