I encountered an issue with a function that either returns a Promise on success or a string on error.
async create(createDebtorDto: CreateDebtorDto): Promise<Debtor> {
console.log("createDebtorDto", createDebtorDto)
try{
const createdDebtor = new this.debtorModel(createDebtorDto);
return await createdDebtor.save();
}catch(err){
console.log('err', err)
return `Unable to create debtor ${err}`;
}
}
During the transpilation process, I encountered this error message:
src/debtors/debtors.service.ts(19,5): error TS2322: Type 'string' is not assignable to type 'Debtor'.
This situation made me question whether it's possible to define a function that returns a Promise in case of success and a String when encountering an error without compromising the benefits of static typing.
Is it feasible to have a function that returns a promise on success and a string on error?