Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

280
Vistas
Vue-router with Typescript and beforeEnter guard, how to use validated data?

I'm using Vue and vue-router with typescript, I have a common case of a single page for a Photo component to be shown, I have a route with a beforeEnter guard that queries my store to see if the requested photo actually exists

    {
        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 my example, I'm already checking in the beforeEnter if the requested photo exists, now if all goes well, the user arrives inside the component.

In my component I'm fetching the photo again from the store using the following line of code

const photo = photoStore.photos.find(p => p.uuid === route.params.id)

Now TS will let me know that this photo could be undefined, since the find operation might return no results, however we already know from the guard step that this photo will indeed be found.

const photo = photoStore.photos.find(p => p.uuid === route.params.id)
const uuid = photo!.uuid

I could use the non-null assertion from Typescript, but ESLint doesn't like that, it's letting me know: ESLint: Forbidden non-null assertion.(@typescript-eslint/no-non-null-assertion)

So I'm wondering, what is the best practice to handle a situation like this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If photo is guaranteed to exist, this is the case for non-null assertion operator. ESLint rule can be temporarily disabled because it doesn't serve a good purpose here.

If photo is not guaranteed to exist, it's incorrect to use non-null assertion operator because this can result in runtime error. This is the case for type guard:

const photo = photoStore.photos.find(p => p.uuid === route.params.id)

if (photo) {
  const uuid = photo.uuid // undefined excluded from photo type
  ...
} else {
  ....
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda