10

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 feathers = require('feathers');

export default function(this: feathers.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.

Victor
  • 3,669
  • 3
  • 37
  • 42
Sean Newell
  • 1,033
  • 1
  • 10
  • 25
  • What is the type of someService? What line does the error occur on? – dbandstra Jun 09 '17 at 20:50
  • Error is on `let data = someService.create({test: 'hello'});` line, and `someService` is defined as a `Service` type as per the `app.service('predefined-service')` call (that type comes from feathers). Feathers services work [by first registering them](https://github.com/feathersjs/feathers#see-it-in-action). – Sean Newell Jun 09 '17 at 20:53

1 Answers1

15

From the Feathers typings:

interface Service<T> extends events.EventEmitter {

  create?(data: T | T[], params?: Params, callback?: any): Promise<T | T[]>;

The create method itself is optional (for whatever reason). If you're sure the method exists you could put the ! operator after, like this:

let data = someService.create!({test: 'hello'});
dbandstra
  • 1,304
  • 9
  • 10
  • 1
    That makes sense, some services won't expose `create` or other REST end points, as user defined services can basically do anything they want. – Sean Newell Jun 09 '17 at 21:06
  • Can someone explain the job of the '!' in this context? Is it just saying "I know it will be 'defined', so don't worry about showing me any warnings... I'm not worried" – Zach Jan 26 '18 at 16:17
  • Yep, exactly. It was added in TS 2.0. They call it the "type assertion operator" or "non-null assertion operator" (though it works with undefined as well). It has no runtime effect. – dbandstra Jan 26 '18 at 23:47