Function overloads with more than 1 parameter

Im trying to overload a function that the first two parameters are string and are not optional, the first parameter should be an union type of strings and the second parameter should also be a union type of strings but these should depende on the first parameter. For example, we have the next function
function callOutsideFunction(module: string, method: string): unknown
function callOutsideFunction(module: string, method: string): unknown
where the module can be climate and date and when i pass any of those have the correct possible methods. I tried overloading the function like this:
function callOutsideFunction(module: 'climate', method: 'climateMethod 1' | 'climateMethod2'): unknown
function callOutsideFunction(module: 'date', method: 'dateMethod 1' | 'dateMethod2'): unknown
function callOutsideFunction(module: 'climate', method: 'climateMethod 1' | 'climateMethod2'): unknown
function callOutsideFunction(module: 'date', method: 'dateMethod 1' | 'dateMethod2'): unknown
but I end up having a union type of all the methods even though I pass certain module as a parameter. Is there any way of fix this?
1 Reply
whatplan
whatplan14mo ago
object with discriminated union
type Foo =
| {
module: 'climate';
method: 'climateMethod1' | 'climateMethod2';
}
| {
module: 'date';
method: 'dateMethod1' | 'dateMethod2';
};

function callOutsideFunction({ module, method }: Foo) {
if (module === 'climate') {
//HOVER METHOD = 'climateMethod1' | 'climateMethod2'
method
} else {
//HOVER METHOD = 'dateMethod1' | 'dateMethod2'
method
}
}
type Foo =
| {
module: 'climate';
method: 'climateMethod1' | 'climateMethod2';
}
| {
module: 'date';
method: 'dateMethod1' | 'dateMethod2';
};

function callOutsideFunction({ module, method }: Foo) {
if (module === 'climate') {
//HOVER METHOD = 'climateMethod1' | 'climateMethod2'
method
} else {
//HOVER METHOD = 'dateMethod1' | 'dateMethod2'
method
}
}
https://tsplay.dev/mMz3bW
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.