[Typescript] Using Generic Context to Avoid Distributive Conditional Types
阿新 • • 發佈:2022-12-12
Let's say we have:
type Fruit = "apple" | "banana" | "orange";
We only want AppleOrBanana
If we do as such:
type Fruit = "apple" | "banana" | "orange"; type AppleOrBanana = Fruit extends "apple" | "banana" ? "apple" | "banana" : never; type tests = [Expect<Equal<AppleOrBanana, "apple" | "banana">>]; // Doesn't work
It doesn't work, it will be never
Way to solve the problem, is using generic type T
type AppleOrBanana = Fruit extends infer T
? T extends "apple" | "banana"
? T
: never
: never;
The reason this is happening is when you use a generic like this, when you pull it out into T
, then what happens is the members of the union distribute across it. T
If you don't do this, then this is no longer in a generic context. This is just itself Fruit
. It compares the entire thing against the entire thing. It says, "Does this contain apple or banana?" It does contain apple or banana, but it also contains orange. What we end up with is never
Solution 2:
type Fruit = "apple" | "banana" | "orange";
type GetAppleOrBanana<T> = T extends "apple" | "banana" ? T : never;
type AppleOrBanana = GetAppleOrBanana<Fruit>;
type tests = [Expect<Equal<AppleOrBanana, "apple" | "banana">>];
This T
now is basically acting as the iterable. You iterate over. We check against apple, check against banana. If we do, then we return T
.