How can I specify in TypeScript that "You can pass in any two objects, as long as their combination satisfies type X"?
For example, consider the following function:
function myFunction(options: {x: number, y: string}){
}
Now, let's say we have another function that needs to call this function using a combination of two objects:
function callMyFunction<A,B>(a:A,b:B){
myFunction({...a,...b})
}
This setup allows us to compile code like the following:
callMyFunction({},{x:1,y:"hello"})
callMyFunction({x:1},{y:"hello"})
callMyFunction({x:1,y:"hello"},{})
However, it will fail to compile with input such as:
callMyFunction({x:1},{}) // Expecting 'y' property
callMyFunction({},{y:"hello"}) // Expecting 'x' property
callMyFunction({},{}) // Both 'x' and 'y' properties missing
We know that we can restrict a generic type using extends
, but is there a way to restrict the combination of two generic types? It would be helpful if something like this were possible:
function callMyFunction<A,B, A&B extends {x:number,y:string}>(a:A,b:B){
myFunction({...a,...b})
}