我目前正在構建一個接受一些路由的組件,并制作一個帶有嵌套路由器視圖的步進器。
我在滿足 TypeScript 方面遇到了一些麻煩。
我正在使用vue-router'sRouteLocationRaw型別。
RouteLocationRaw是string兩個交集型別的并集,定義為
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;
}
我想做的是將當前路由的名稱與傳遞給組件的名稱進行比較,如下所示
const activeRoute = computed(() => props.routes.find((propRoute) => propRoute.name === route.name))
這個邏輯按我的意愿作業,但 TypeScript 抱怨。使用上述方法,我得到以下錯誤。
Property 'name' does not exist on type 'RouteLocationRaw'.
Property 'name' does not exist on type 'string'.
TypeScript 似乎自動假定型別是一個字串,它是聯合的第一部分。假設已經是一件奇怪的事情,但是縮小到字串之外也沒有幫助。
如果我添加一個用于處理屬于type stringTypeScript 的路由的案例,仍然無法識別這name可能是route.
Property 'name' does not exist on type '(RouteQueryAndHash & LocationAsPath & RouteLocationOptions) | (RouteQueryAndHash & LocationAsRelativeRaw & RouteLocationOptions)'.
Property 'name' does not exist on type 'RouteQueryAndHash & LocationAsPath & RouteLocationOptions'.
uj5u.com熱心網友回復:
我將把你的代碼簡化為這個,它有同樣的錯誤。
declare const propRoute: RouteLocationRaw // the current route, lets say
if (propRoute.name === 'foo') {
console.log('foo is active')
}
現在要訪問任何值的屬性,該型別必須宣告該屬性。當您訪問聯合的屬性時,該聯合的所有成員都必須宣告這一點。所以打字稿不假設值是string,它告訴你它可能是 a string,如果是,那么這個屬性訪問沒有任何意義。
因此,要訪問該name屬性,您需要將聯合范圍縮小到僅支持該name屬性的型別。因此,您必須過濾掉string并且您必須過濾掉缺少該屬性的物件屬性。
這可能看起來像這樣:
if (
typeof propRoute !== 'string' && // filter out string.
'name' in propRoute && // require the `name` property.
propRoute.name === 'foo' // check the name proeprty.
) {
console.log('foo is active')
}
看游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507930.html
