Typescript Object possibly undefined after type security error TS2532
I am using Typescript 2.3.4
, Node.JS 8.0.0
and Feathers framework (version 2.1.1
). I am doing an express route that uses a service, and when I try to use the service after getting a singleton instance in a nib application, Typescript throws error TS2532: The object might be an "undefined" error even after explicit type protection.
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 also tried to write someService!.create...
, but that didn't work either.
source to share
From writing pens :
interface Service<T> extends events.EventEmitter {
create?(data: T | T[], params?: Params, callback?: any): Promise<T | T[]>;
The method create
itself is optional (for whatever reason). If you are sure that the method exists, you can place a statement !
after that, for example:
let data = someService.create!({test: 'hello'});
source to share