Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 471
Sean Newell Avatar asked Jun 09 '17 19:06

Sean Newell


People also ask

How can you tell if a TypeScript variable is not undefined?

Sometimes the TypeScript compiler isn't able to determine what type of value it may at a certain point. By adding the exclamation mark ( ! ) at the end, you let the TypeScript compiler that there is no way this variable will be undefined or null.

How do I fix TypeScript object is possibly undefined?

The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.

How do you prevent undefined in TypeScript?

To avoid undefined values when using or accessing the optional object properties, the basic idea is to check the property value using an if conditional statement or the optional chaining operator before accessing the object property in TypeScript.


1 Answers

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'});
like image 119
dbandstra Avatar answered Oct 13 '22 22:10

dbandstra