Angular 14 pathMatch Type 'string' is not assignable to type '"full" | "prefix"' Error
Asked Answered
R

2

6

Just upgraded to Angular 14, getting error:

Types of property 'pathMatch' are incompatible.
        Type 'string' is not assignable to type '"full" | "prefix"'.

Calling from:

import { Routes as routes } from './routes';
@NgModule({
  imports: [
    RouterModule.forChild(routes)
    ]...})

with routes being

export const Routes = [
  {
    path: '',
    redirectTo: '/signup',
    pathMatch: 'full'
  }]

The whole thing worked perfectly on Angular 10. Any ideas ?

Rattat answered 5/10, 2022 at 17:25 Comment(0)
D
18

You can create a type and cast to it:

type PathMatch = "full" | "prefix" | undefined;

const routes = [
  {
    path: 'achievements',
    component: AchievementOverviewComponent,
    pathMatch: 'full' as PathMatch
  }
]

More info in a related answer: Typescript Type 'string' is not assignable to type.

Defensible answered 8/10, 2022 at 21:47 Comment(2)
Do you have any idea why this is ? In the link, they talk about how to solve the specific problem, but they don"t give a hint to why that genereal phenomenon appears. In this case, I would think that "full" would be one of the explicit possibilities as it is a specific string. (pathMatch being derived from Type string). Also, why did it work in previous angular versions ?Rattat
@Rattat It's to do with TypeScript, not angular in itself. You'd be better off asking this as a separate question or as a comment on the answer I linked to. There are many who are much better suited to answer you.Defensible
D
13

Just define routes as Routes, so TypeScript will know that pathMatch is 'full', 'prefix' or undefined.

This is better than the currently accepted (and working) answer, because it also type checks the other properties.

import { Routes } from '@angular/router';

export const routes: Routes = [
  {
    path: '',
    redirectTo: '/signup',
    pathMatch: 'full'
  }]
Davao answered 2/3, 2023 at 10:30 Comment(2)
Huh, this is much better than the accepted one.Meningitis
I second this. This is the better answer, since there is no need for ad hoc type creation.Elspet

© 2022 - 2025 — McMap. All rights reserved.