I'm having a hard time looking for a solution to deal with the exponential growth of function overloads in typescript, here's the problem:
Say I have a findOne function that gets an id, looks in the database, and finds a Person:
findOne(id):Promise<Person| undefined> {
return query().findById(id);
}
Now I can have a variable added to throw if Person is not found (id does not exist) and make sure that findOne is not returning undefined if the variable is passed;
findOne(id):Promise<Person|undefined>;
findOne(id,orFail:true):Promise<Person>;
findOne(id,orFail?:true):Promise<Person|undefined> {
if (orFail){
return query().findById(id).throwIfNotFound();
}
return query().findById(id);
}
Now, what happens if I have another variable that decides if a field of person should be joined or not? yes, it multiplies the return types by 2 (adding another possibility for each previous one to have a joined field or not)
Again, If I have more variables, each one will multiply it by 2, so I think I will have 2^optionalVarialesCount overloads of the findOne function.
Is there a better way to do this? I don't want to overload 16 times for 4 optional variables, It really makes the code messy.