My goal is to develop a function that takes two parameters. The first parameter is a union type, and the second parameter's type depends on the type of the first one.
For instance:
type Fruit = "Orange" | "Apple" | "Banana";
function doubleFruit<T extends Fruit, K extends T>(fruit1: T, fruit2: K) {
// At this point,
// both fruit1 and fruit2 should be the same fruit
}
The following statements behave as expected
// Error occurs because Orange is not the same as Apple or Banana
doubleFruit("Orange", "Apple");
doubleFruit("Orange", "Banana");
// Runs smoothly, as both are the same fruit
doubleFruit("Apple", "Apple");
However, when the first parameter is dynamic, there is a strange outcome
function run(x: "Orange" | "Apple") {
// Shouldn't work since x could vary
doubleFruit(x, "Orange");
}
It seems that due to x
being either Orange
or Apple
, having the second parameter as Orange
does not meet the requirement of both parameters being identical.
Edit: Here's my desired objective
type Fruit = "Orange" | "Apple" | "Banana";
function doubleFruit<T extends Fruit, K extends T>(fruit1: T, fruit2: K) {
// At this point
// both fruit1 and fruit2 should be the same fruit
}
function run(x: "Orange" | "Apple") {
// I want this to be valid:
// Regardless of the value of x, the other parameter must be the same,
// and therefore should be accepted
doubleFruit(x, x);
// But these shouldn't be allowed:
// Since x can vary, specifically passing only one of the values should not work
doubleFruit(x, "Orange")
doubleFruit(x, "Apple")
}
I am looking for a way to achieve the above-described functionality.