How can I modify a function based on generics to omit or make optional the last parameter?
interface Requests {
post: {
data: {
test: number
}
}
patch: {
data: {
test?: number
}
}
get: never
}
const makeRequest = <Method extends keyof Requests>
(method: Method, data: Requests[Method] extends {data: infer Data} ? Data : never)
=> { /* ... */ }
makeRequest('post', { test: 1 }) // this is correct as the second parameter is required
In the case of 'patch' method where the 'data' object has no required fields, it should be possible to not pass anything as the second parameter.
makeRequest('patch', {})
makeRequest('patch') // an error is thrown: Expected 2 arguments, but received 1
For methods like 'get' where the second parameter is irrelevant since there is no data structure defined, it should either be completely omitted or at least not require an empty object.
makeRequest('get') // error: Expected 2 arguments, but got 1