As I utilize Vue along with vue-router and typescript, a common scenario arises where a single page is dedicated to displaying a Photo component. A route includes a beforeEnter
guard that checks my store to verify the existence of the requested photo.
{
name: 'photo',
path: '/photos/:id',
meta: {requiresAuth: true},
component: () => import('@/pages/Photo.vue'),
beforeEnter: (to, from, next) => {
const photos = usePhotos();
const requestedPhoto = photos.$state.photos.findIndex(p => p.uuid === to.params.id)
return requestedPhoto === -1 ? next({name: 'home'}) : next()
},
}
In this particular case, the beforeEnter
function serves to confirm the presence of the desired photo. Once the user successfully navigates to the component, the actual photo is fetched from the store within the component using the code snippet below:
const photo = photoStore.photos.find(p => p.uuid === route.params.id)
Nevertheless, Typescript points out that the retrieved photo may be undefined due to the possibility of no match during the find operation. Given our prior check in the guard step, we can safely assume that the photo will always be found.
const photo = photoStore.photos.find(p => p.uuid === route.params.id)
const uuid = photo!.uuid
The non-null assertion approach offered by Typescript triggers an ESLint warning indicating its prohibition:
ESLint: Forbidden non-null assertion.(@typescript-eslint/no-non-null-assertion)
Thus, the question arises as to what would be considered the best practice for handling such a situation?