Here is my Interface ISomeModel
export interface ISomeModel {
id?: string;
title: string;
description: string;
// .... other fields
}
Here is my class SomeService
class SomeService {
static fromJsonAndId(json: any, id?: string): ISomeModel {
return {
id: id,
title: json.title,
description: json.description,
// ..... other fields
} as ISomeModel;
}
handleFirestoreError(error: any) {
if (error.code === 'permission-denied' || error.code === 'unauthenticated') {
tokenService.logout(true);
} else {
throw error;
}
}
create(someModel: ISomeModel): Promise<ISomeModel | void> {
return db
.add(someModel)
.then((doc) => SomeService.fromJsonAndId(someModel, doc.id))
.catch((err) => this.handleFirestoreError(err));
}
}
export default new SomeService();
Here is my react component where I am using the create method:
const someInstance = await someService.create(someModelObj);
console.log('created', someInstance.id);
But I get this error in my ide(webstorm):
The create
function would either return ISomeModel
instance or throw error. It can never return void. So why am I getting that error? And how do I fix it?
CodePudding user response:
const someInstance = await someService.create(someModelObj) as ISomeModel
or maybe you can use a typeof to detect is a void or a ISomeModel
CodePudding user response:
Here you can explicitly tell TypeScript that when an error is being handled, you return a null
value. So you can either have an object with type definition of ISomeModel
or a null
value (Here you can use optional chaining operator - ? to make sure you're only accessing the object if it exists). The code will look like below (I have mocked some objects like db
and tokenService
) :-
export interface ISomeModel {
id?: string;
title: string;
description: string;
// .... other fields
}
type Nullable<T> = T | null;
const db = {
add:(someModel:ISomeModel)=>Promise.resolve({id:'sd',title:'df',description:'fdf'})
}
const tokenService = {
logout:(someboolean:boolean)=>{}
}
class SomeService {
static fromJsonAndId(json: any, id?: string): ISomeModel {
return {
id: id,
title: json.title,
description: json.description,
// ..... other fields
} as ISomeModel;
}
handleFirestoreError(error: any) {
if (error.code === 'permission-denied' || error.code === 'unauthenticated') {
tokenService.logout(true);
return null;
} else {
throw error;
}
}
create(someModel: ISomeModel): Promise<Nullable<ISomeModel>> {
return db
.add(someModel)
.then((doc:any) => SomeService.fromJsonAndId(someModel, doc.id))
.catch((err:any) => this.handleFirestoreError(err));
}
}
export default new SomeService();
const someService = new SomeService();
try{
const someInstance = await someService.create({ id: '3434343',
title: 'Some object title',
description: 'some object description'});
console.log('created', someInstance?.id);
}
catch(err:any){
// handle other errors
}
Also here is the typescript playground