I am currently working on a project where I need to create a component that takes in routes and generates a nested router view within a stepper.
However, I am facing challenges with TypeScript integration.
The component uses the RouteLocationRaw
type from vue-router
.
RouteLocationRaw
is a combination of string
and two intersection types, defined as:
export declare type RouteLocationRaw = string | (RouteQueryAndHash & LocationAsPath & RouteLocationOptions) | (RouteQueryAndHash & LocationAsRelativeRaw & RouteLocationOptions);
export declare interface RouteQueryAndHash {
query?: LocationQueryRaw;
hash?: string;
}
export declare interface LocationAsPath {
path: string;
}
export declare interface RouteLocationOptions {
replace?: boolean;
force?: boolean;
state?: HistoryState;
}
export declare interface LocationAsRelativeRaw {
name?: RouteRecordName;
params?: RouteParamsRaw;
}
My goal is to compare the current route's name with the names passed into the component using the following code:
const activeRoute = computed(() => props.routes.find((propRoute) => propRoute.name === route.name))
Although this logic functions correctly, TypeScript raises errors. When attempting to narrow down the type, I encounter the following issues:
Property 'name' does not exist on type 'RouteLocationRaw'.
Property 'name' does not exist on type 'string'.
It seems that TypeScript automatically assumes the type to be a string due to it being the first part of the union, but further narrowing is not beneficial.
Even when handling scenarios for routes of type string
, TypeScript still fails to recognize that 'name' could be a property of 'route'.
Property 'name' does not exist on type '(RouteQueryAndHash & LocationAsPath & RouteLocationOptions) | (RouteQueryAndHash & LocationAsRelativeRaw & RouteLocationOptions)'.
Property 'name' does not exist on type 'RouteQueryAndHash & LocationAsPath & RouteLocationOptions'.