In my code, there is a function called myFunction
that takes in two parameters:
key
which can be either"mode"
,"foo"
, or"bar"
value
of typeany
. However, if thekey
is"mode"
, then thevalue
must be of typeMode
I attempted to implement function overloading for this, but unfortunately, it did not work as intended. My goal was to have one signature specifically for when key
is equal to "mode"
, and another "catch-all" signature for all other cases.
export const KEYS = Object.freeze({
mode: "mode",
foo: "foo",
bar: "bar",
});
export type Key = (typeof KEYS)[keyof typeof KEYS];
export const MODES = Object.freeze({
TABLE: "table",
CARDS: "cards",
});
export type Mode = (typeof MODES)[keyof typeof MODES];
function myFunction(
key: "mode",
value: Mode
): void;
function myFunction(key: Key, value: any): void {
console.log(key, value)
}
myFunction("mode", "cards"); // OK
myFunction("foo", 123); // Argument of type '"foo"' is not assignable to parameter of type '"mode"'.
myFunction("bar", "test"); // Argument of type '"bar"' is not assignable to parameter of type '"mode"'.
Why isn't my implementation working as expected? Should I provide more explicit signatures for each case?