Friday 9 June 2017

Typescript Object is possibly undefined after type guard error TS2532

I'm using Typescript 2.3.4, Node.JS 8.0.0, and the feathers framework (version 2.1.1). I am making an express route that uses a service, and when I try to use the service after grabbing the singleton instance on the feathers app, Typescript is throwing an error TS2532: Object is possibly 'undefined' error, even after an explicit type guard.

routes.ts

import { Application } from 'feathers';

export default function(this: Application) {
  const app = this;

  app.post(
    '/donuts',
    async (req, res) => {
      const someService = app.service<any>('predefined-service');

      if(typeof someService === "undefined" || !authService) {
        res.redirect('/fail');
        return;
      }

      try {
        let data = someService.create({test: 'hello'});
        console.log(data);
        res.redirect('/success');
      } catch(err) {
        res.redirect('/fail');
      }
    }
}

I've also tried writing someService!.create... but that didn't work either.

Thanks for reading, any help appreciated <3<3



via Sean Newell

No comments:

Post a Comment