I'm trying to write a function main that takes an object opts, and returns another object. opts has two optional properties a and b.
If a is present, the returned object should have a property aResult. If b is present, the returned object should have a property bResult. If both a and b are present on opts, then both aResult and bResult should be present on the returned object.
I can achieve this with overloads:
interface usesA {
a: string;
}
interface usesB {
b: string;
}
interface aReturnType {
aResult: string;
}
interface bReturnType {
bResult: string;
}
function main(opts: usesA): aReturnType;
function main(opts: usesB): bReturnType
function main(opts: usesA & usesB): aReturnType & bReturnType;
// implementation omitted
But this gets quite long-winded if I want to add more optional properties: c which maps onto cResult, d which maps onto dResult etc.
Is there a more succinct way of doing this, e.g. using a generic function?