Skip to content

Make routes typesafe #188

@halbekanne

Description

@halbekanne

Suggestion generated by phind.com using ChatGPT 4 model:

Prompt:
In Angular, I saw that routes are not typesafe per default, what I mean is that when I define a route 'apple' and somewhere else I navigate to 'apple' but I have a typo, the IDE will not report that error. How can I fix this, are there solutions or libraries that make routes in Angular typesafe?

Answer:
To make routes in Angular more type-safe, you can use a combination of TypeScript enums, computed property types, and external libraries like typesafe-routes. Here's a step-by-step guide to achieving type-safe routes in Angular:

  1. First, create a separate file for your routes, e.g., routes.ts. In this file, define a class AppRoutes, which will contain your route definitions. Use the typesafe-routes library to define your routes with path parameters and their types. For example:
import { createRoute, intParser } from 'typesafe-routes';

class AppRoutes {
  static detailsOverview = createRoute('details');
  static detail = AppRoutes.detailsOverview.addChild('/:id', { id: intParser });
}

In this example, we define a route detailsOverview with the path details, and a child route detail with the path parameter id of type number [Source 11].

  1. Update your app-routing.module.ts to use the routes defined in routes.ts. Import the AppRoutes class and use the template property to get the path string for each route:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppRoutes } from './routes';
import { DetailsComponent } from './details/details.component';

const routes: Routes = [
  { path: AppRoutes.detailsOverview.template, component: DetailsComponent },
  { path: AppRoutes.detail.getChild('detail').template, component: DetailsComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

Here, we use the getChild method to access the child route detail and its template property to get the path string [Source 11].

  1. In your component templates, use the AppRoutes class to generate type-safe route paths:
<a [routerLink]="[AppRoutes.detailsOverview.template]">Details Overview</a>
<a [routerLink]="[AppRoutes.detail.getChild('detail').createPath({ id: 123 })]">Detail 123</a>

This way, you ensure that your route paths are consistent and type-safe [Source 11].

  1. To read the entered parameters in a type-safe way, use the parseParams method from typesafe-routes:
import { ActivatedRoute } from '@angular/router';
import { AppRoutes } from '../routes';

@Component({...})
export class DetailsComponent implements OnInit {
  id: number;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    const parsedParams = AppRoutes.detail.getChild('detail').parseParams(this.route.snapshot.params);
    this.id = parsedParams.id;
  }
}

By using the parseParams method, you ensure that the parameters are type-safe and consistent with your route definitions [Source 11].

By following these steps, you can achieve type-safe routes in Angular, reducing the risk of typos and mismatches in your route paths and parameters.

Source 11

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    📋 Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions