I am grappling with a generic function that returns another function.
While typing it, there might be required keys. These required keys are optional for the initial function, but become mandatory for the subsequent function if they were not provided initially. However, if they are provided in the first function, they then become optional for the second function (for overwriting purposes).
Here is what I have attempted so far, but unfortunately, I have not been able to solve it yet.
function myFunc<T>(opts?: Partial<T>) {
// this typing is incorrect, and I am struggling to fix it
return (moreOpts: Omit<T, keyof typeof opts> & Partial<T>) => {
// perform some actions
}
}
type TestType = {
name: string;
age: number;
}
const test1 = myFunc<TestType>({ name: 'John Doe' }) // no error
test1() // error -- age is required
const test2 = myFunc<TestType>() // no error
test2({ name: 'John Doe', age: 23 }) // no error
const test3 = myFunc<TestType>({ name: 'John Doe', age: 23 }); // no error
test3({ name: 'Jane Doe' }) // no error
const test4 = myFunc<TestType>({ name: 'John Doe' }); // no error
test4({ name: 'Jane Doe' }) // error -- age is required
const test5 = myFunc<TestType>({ name: 'John Doe', age: 23 }); // no error
test5() // no error