I am trying to create a function that takes two parameters, first is a union type, second is type that depends on the type of the first parameter.
For example:
type Fruit = "Orange" | "Apple" | "Banana";
function doubleFruit<T extends Fruit, K extends T>(fruit1: T, fruit2: K) {
// When execution reaches herer
// both fruit1 and fruit2 need to be the same fruit
}
Now, These statements work as expected
// Gives error since Orange is not same as Apple neither banana
doubleFruit("Orange", "Apple");
doubleFruit("Orange", "Banana");
// Runs peacefully, since both are same fruit
doubleFruit("Apple", "Apple");
But when the first parameter is dynamic, something strange happens
function run(x: "Orange" | "Apple") {
// Should not work, since x could be anything
doubleFruit(x, "Orange");
}
I assume that since x
could be either Orange
or Apple
, the second parameter being Orange
does not follow the criteria of both parameters being same.