'Create Type based off of paramter type
I have a generic function that returns another function.
When typing it, it might have required keys. Those required keys are optional for the first functional, but required for the second function IF they are not provided in the first. IF they are provided in the first function, they are then optional in the second (for overwriting)
Below is what I have tried, but haven't been able to figure it out.
function myFunc<T>(opts?: Partial<T>) {
// this typing is wrong, but I don't know what it should be
return (moreOpts: Omit<T, keyof typeof opts> & Partial<T>) => {
// do stuff
}
}
type TestType = {
name: string;
age: number;
}
const test1 = myFunc<TestType>({ name: 'John Doe' }) // no error
test1() // error -- needs age
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 -- needs age
const test5 = myFunc<TestType>({ name: 'John Doe', age: 23 }); // no error
test5() // no error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
