I am working on defining types for a simple function called fun
.
Below are the interfaces for the input and response:
interface Input {
test1?: true
test2?: true
test3?: true
}
interface Res {
test1?: string
test2?: string
test3?: string
}
Now, let's take a look at the implementation of the function:
fun(input: Input): Res {
const res: Res = {}
if (input.test1) {
res.test1 = 'jupi'
}
if (input.test2) {
res.test2 = 'jupiX2'
}
if (input.test3) {
res.test3 = 'jupiX3'
}
return res
}
The current types ensure that the response of the function fun
will always be of type Res
, regardless of the input provided. Additionally, the implementation of fun
will return values for each key passed in the input
.
One approach to connect input and response types is using Function Overloads.
An example of this approach is shown below:
// Function Overloads for 'fun'
// ...
In this implementation, the RequireMany
type is used, where:
type RequireMany<T, Keys extends keyof T = keyof T> = Pick<T, Extract<keyof T, Keys>>
Given that I plan to have at least 7 keys in my input
, I am curious to know:
Is there a more efficient or generic way to type the fun
function rather than using multiple Function Overloads?